从popup组件看vue中的 sync的应用

父子组件嵌套时候 vue支持的是单向数据流,并不是双向数据绑定的,
也就是常见的父组件通过props 传递数据进去,子组件通过emit派发事件,但是子组件是不能修改props的,因为这个数据是父组件的,

但是有的情况需要双向绑定,例如 popup弹层,外侧通过 某操作触发弹层显示传递props进去,
popup组件内部会点击mask层 来取消显示,

代码说明

组件调用方式

<simpleCashier :cashier-visible.sync="cashierVisible"/>

内部组件改变属性方式

  props: {
    cashierVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
    }
  },
  computed: {
    show: {
      get() {
        return this.cashierVisible
      },
      set(val) {
        this.$emit('update:cashierVisible', val)
        console.log(val)
      }
    }
  },

需要注意的点有

1 外部传递进来的 cashierVisible ,内部props接受的cashierVisible 后, 不可直接使用,因为当点击mask层组件会修改这个属性,就违背了vue的单向数据流原则,会报错

[Vue warn]: Avoid mutating a prop directly since the value will be 
overwritten whenever the parent component re-renders. Instead, 
use a data or computed property based on the prop's value. Prop being mutated: "cashierVisible"

2 按照上面说的我们把外部传递进来的cashierVisible 属性换成计算属性 show,需要写set,get 如下

  computed: {
    show: {
      get() {
        return this.cashierVisible
      },
      set(val) {
        this.$emit('update:cashierVisible', val)
        console.log(val)
      }
    }
  },

否则会报错

[Vue warn]: Computed property "show" was assigned to but it has no setter.

在set里通过 this.$emit('update:cashierVisible', val) 把属性改变传递出去,完成~ 不能再set里直接给show赋值,否则会报第一条错误

posted @ 2018-05-04 11:03  _白马非马  阅读(1739)  评论(0编辑  收藏  举报