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

查看:141
本文介绍了javascript - 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/

解决方案

已经解决,使用watch即可。详见: http://jsfiddle.net/h313j5sh/7/

谢谢各位

这篇关于javascript - V-model绑定数组的时候为啥会不能更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆