Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save 337547038/e5291d17a7d194bd72d4b0f6a02f0aa0 to your computer and use it in GitHub Desktop.
Save 337547038/e5291d17a7d194bd72d4b0f6a02f0aa0 to your computer and use it in GitHub Desktop.
Vue中v-model无法动态更新对象数组数据问题
大致代码如下:
<input type='text' v-model='value'>{{value}}
data(){
return {
value:['1','2']
}
},
methods:{
test(){
this.value[0]='3';
this.$emit('input',this.value)
}
}
emit后实际上value显示的值并没有同步更新,因为vue监听的是this.value没有监听this.value的子项,所以直接改变子项不会触发更新,解决办法:
1.利用vue的set方法
this.$set(example.item,indexOfItem,newValue)或Vue.set(..)
结合上例子便是this.$set(this.value,'0','3')
2.Array.prototype.splice方法
example.item.splice(indexOfItem,1,newValue)
即this.value.splice(0,1,'3')
意思为从第0个开始,删除一个元素,并向数组中添加新元素3,可参考splice用法
以上两种方法都可以实现相同的效果,将触发状态更新;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment