zoukankan      html  css  js  c++  java
  • 从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赋值,否则会报第一条错误

  • 相关阅读:
    js
    第三方jar包导入unity
    xcode打包苹果应用遇到的问题及解决方法
    ios打包unity应用以及配置签名
    unity打包安卓应用及生成签名
    Unity实现用户条款弹窗及登录
    Unity协程实现伪加载页面
    Unity配置安卓开发环境
    Unity中用Mono插件解析xml文件
    Excel关联xml文件
  • 原文地址:https://www.cnblogs.com/WhiteHorseIsNotHorse/p/8989625.html
Copyright © 2011-2022 走看看