V-model绑定数组的时候为啥会不能更新?

Array1和Array2都是通过v-model绑定到同一个数组变量上,为啥Array1更新的时候Array2不能同步更新?

运行效果:

可以看到Array1都已经emit了input,但是Array2的updated为啥没有被调到?


模版代码:

<script src="//unpkg.com/vue/dist/vue.js"></script>
<div id="app">
  <div>
    Array1: <array-input v-model="result" />
  </div>
  <div>
    Array2: <array-input v-model="result" />
  </div>
  <div>
    result: {{result}}
  </div>
</div>

<h3>logs:</h3>
<ol id="logs"></ol>

script代码:


let ArrayInputId = 0;
const ArrayInput = {
  props: {
    value: {
      type: Array,
      default: () => [],
    },
  },
  template: '<input type="text" @input="onInputText" placeholder="Enter comma separated array" />',
  data(){
    return {
      id: ++ArrayInputId,
      text: '',
    }
  },
  methods: {
    onInputText(e){
      this.text = e.target.value 

      let newValue = this.text.split(',')
      log(`ArrayInput#${this.id} emit input: ${JSON.stringify(newValue)}, text: ${this.text}`)
      this.$emit('input', newValue)
    }
  },
  updated(){
    log(`ArrayInput#${this.id} updated. value: ${JSON.stringify(this.value)}, text: ${this.text}`)
    if (this.text !== this.value.join(',')){
      this.text = this.value.join(',')
      // this.$forceUpdate() // $forceUpdate not help ...
    }
  }
}


new Vue({
  components: {
    'array-input': ArrayInput,
  },
  data(){
      return {
        result: [],
    }
  }
}).$mount('#app')



function log(msg){
    console.log(msg)
  let li = document.createElement('li')
  li.innerText = msg
  document.getElementById('logs').appendChild(li)
}

在线代码见 http://jsfiddle.net/h313j5sh/3/

阅读 8.7k
2 个回答
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
    <div id="app">
        <ul>
            <li v-for="i in 3">
                <array-input v-model="result" />
            </li>
            <li>{{ result }}</li>
        </ul>
    </div>

    <template id="ArrayInput">
        <input type="text" v-model="text" />
    </template>

    <script src="http://cdn.bootcss.com/vue/2.1.8/vue.min.js"></script>

    <script>
        Vue.component('ArrayInput', {
            template: '#ArrayInput',
            props: {
                value: Array
            },
            computed: {
                text: {
                    get() {
                        return this.value.join(',')
                    },
                    set(val) {
                        this.$emit('input', val ? val.split(',') : [])
                    }
                }
            }
        })

        new Vue({
            el: '#app',
            data() {
                return {
                    result: []
                }
            }
        })
    </script>
</body>
</html>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题