vue两个select用一个字段绑定出现的问题?

<div id="app">
  <select v-model="cur" @change="show">
    <option value>请选择</option>
    <option :value="item.id" v-for="item in arr">{{item.text}}</option>
  </select>
  <select v-model="cur" @change="show">
    <option value>请选择</option>
    <option :value="item.id" v-for="item in arr2">{{item.text}}</option>
  </select>
</div>

var vm = new Vue({
        el: '#app',
        data: {
            cur: '',
            arr:[
              {id: 1,text:'hhh'},
              {id: 2,text:'xxx'}
            ],
            arr2:[
              {id: 3,text:'a3'},
              {id: 4,text:'a4'}
            ]
        },
        methods: {
            show: function() {
                console.log(this.cur)
            }
        }
    })

页面中有两个选项用一个字段,使用vue做了之后,选择其中一个,两个都变成了空。我想实现的效果是选择其中一个,另一个变成“请选择”,该如何实现?

阅读 2.5k
2 个回答

你的v-model绑定不同的值就行了,绑定同一个值,修改其中一个必然会影响到另一个。

  <div id="app">
    <select v-model="cur1" @change="show(1)">
      <option value>请选择</option>
      <option :value="item.id" v-for="item in arr">{{item.text}}</option>
    </select>
    <select v-model="cur2" @change="show(2)">
      <option value>请选择</option>
      <option :value="item.id" v-for="item in arr2">{{item.text}}</option>
    </select>
  </div>
  <script>
  var vm = new Vue({
          el: '#app',
          data: {
              cur1: '',
              cur2: '',
              arr:[
                {id: 1,text:'hhh'},
                {id: 2,text:'xxx'}
              ],
              arr2:[
                {id: 3,text:'a3'},
                {id: 4,text:'a4'}
              ]
          },
          methods: {
              show: function(index) {
                let ind = index === 1 ? 2 : 1
                this['cur' + ind] = ''
                console.log(this.cur1)
                console.log(this.cur2)
              },
              submit: function () {
                let cur = this.cur1 !== '' ? this.cur1 : this.cur2
                if (cur !== '') {
                  // 提交
                }
              }
          }
      })
    </script>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题