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赋值,否则会报第一条错误

  • 相关阅读:
    eclipse实现热部署和热启动
    java.sql.SQLException: Incorrect string value: 'xF0x9Fx98x87<b
    Springboot 热部署中存在冲突的问题
    在执行save操作时候出现的诡异!
    富文本编辑器选择使用
    Springboot 1.5.x版本上读取自定义配置文件问题
    Springboot中静态资源和拦截器处理(踩了坑)
    表单验证——jquery validate使用说明【另一个教程】
    表单验证——jquery validate使用说明
    注册页面
  • 原文地址:https://www.cnblogs.com/WhiteHorseIsNotHorse/p/8989625.html
Copyright © 2011-2022 走看看