vue 中 .sync 修饰符的使用(子组件修改父组件的值)及.sycn 无效的原因

297 阅读1分钟

需求:当我们子组件需要修改父组件参数时。

方法一 -- 常规方法

父组件:

     <child :money="money" @handle='handle()'></child>
     
     //js
     return{
      money:10,
    }
    handle(){
      this.money = 200;
    }

子组件:

    <div>
          现在是 ---{{money}}元
          <br/>
          <button @click="handle">修改</button>   
    </div>
    
    //js
      props: {
        money: null
      },
      methods: {
        handle() {
          this.$emit('handle', 200)
        }
      }

方法二 -- .async

父组件

    <!-- <child :money="money" @update:money= fn()></child> --原生写法-->
    <child :money.sync="money"></child>
    
    //js
    
    

子组件-html不变

<div>
      现在是 ---{{money}}元
      <br/>
      <button @click="handle">修改</button>   
</div>
//js
props: {
        money: null
      },
handle() {
      this.$emit('update:money',200)//如果不是update,则sync修饰符无效
}

注意:
这种写法-<child :money.sync="money"></child>this.$emit里面的update必须是----update
如果是<child :money="money" @aa:money= fn()></child>this.$emit里面的update可以随便定义,比如:aa