javascript - V-model绑定数组的时候为啥会不能更新?
PHP中文网
PHP中文网 2017-04-11 12:33:04
[JavaScript讨论组]

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

运行效果:

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


模版代码:


Array1:

Array2:

result: {{result}}

logs:

    script代码:

    
    let ArrayInputId = 0;
    const ArrayInput = {
      props: {
        value: {
          type: Array,
          default: () => [],
        },
      },
      template: '',
      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/

    PHP中文网
    PHP中文网

    认证0级讲师

    全部回复(0)
    热门教程
    更多>
    最新下载
    更多>
    网站特效
    网站源码
    网站素材
    前端模板
    关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
    php中文网:公益在线php培训,帮助PHP学习者快速成长!
    关注服务号 技术交流群
    PHP中文网订阅号
    每天精选资源文章推送

    Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号