首页 > 编程 > JavaScript > 正文

详解vue中的父子传值双向绑定及数据更新问题

2019-11-19 11:21:15
字体:
来源:转载
供稿:网友

在进行父子组件传值时,用到子组件直接控制父组件中的变量值以及在vue中直接更改对象或者数组的值,视图未发生变化的解决办法,当时完成项目时,一直未找到原因,修改了好久。

1.父子组件传值双向绑定

在传递给子组件中的变量上使用.sync修饰符,就能够实现父子传值的双向绑定

<!-- 父组件 --><template> <div class="audioCate"> <child :show.sync="showModel" @closeModel="handleCloseModel"></child> </div></template><script> import child from './child' export default{ components: {  child, } data() {  return {  showModel: false  } }, methods: {  handleCloseModel() {  this.showModel = false;  } } }</script><!-- 子组件 --><template> <div class="cate" @click="handleClick"> <div></div> </div></template><script> export default{ props: {  show: Boolean, }, data() {  return {  showModel: false  } }, methods: {  handleClick() {  /* 直接更新父组件中的showModel值 */  this.$emit('update:show', false);  /* 或者调用父组件中的方法对showModel进行更改 */  /* this.$emit('closeModel'); */  } } }</script>

2.修改对象或数组中的键,视图未发生变化

使用$set方法进行修改,官方文档中也有说明


当时我是直接对数组中的值进行修改,但是视图没有发生变化

<script> export default{ data() {  return {  item: {   title: '222'  },  options: [11, 22],  list: [   {   title: '2222'   }  ]  } }, created() {  /* 对于对象,第一个为要修改的对象,第二个参数为对象的键,第三个为要修改的键对应的值 */  this.$set(this.item, 'title', '2200');  /* 对于对象,第一个为要修改的数组,第二个参数为数组索引,第三个为要修改的索引对应的值 */  this.$set(this.options, 0, 33);  /* 对于数组里包含对象,可以利用循环对其进行修改 */  this.list.forEach(item => {  this.$set(item, '_disableExpand', true);  });  /* 对于数组里包含对象,也可以利用Object.assign对其进行修改 */  this.list[0] = Object.assign({}, this.list[0], { num: 10 });  this.$set(this.list, 0, this.list[0]); }, }</script>

也可以直接进行修改后对页面进行强制刷新,使用$forceUpdate()方法

this.options[0] = 100;this.$forceUpdate();

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表