vue的sync语法糖的使用(父子组件双向绑定)

sync的使用场景

有些时候子组件需要修改父组件传递过来的prop,要去改变父组件的状态的时候就需要使用aync,sync修饰符可以双向绑定父子组件中的数据。

使用:
父组件

javascript 复制代码
<template>
  <div>
    请问
    <el-button @click="fatherHander">切换-父按钮</el-button>
    <test-com :ishow.sync="flag"></test-com>
  </div>
</template>
 
<script>
import testcom from "../components/test-com.vue"
  export default {
    data(){
      return{
        flag:true
      }
    },
    components:{
      'test-com':testcom
    },
    methods:{
      fatherHander(){
        this.flag=!this.flag
      }
    },
  }
</script>

子组件

javascript 复制代码
<template>
    <div v-if="ishow" class="demo">
        <h2>我是子组件</h2>
        <h3>我是子组件中的信息</h3>
        <h3>我是子组件中的信息</h3>
        <el-button @click="sonHander">切换-子组件按钮</el-button>
    </div>
</template>
 
<script>
    export default {
        props:{ 
            ishow:{
                type:Boolean
            }
        },
        methods:{
            sonHander(){
                // 注意单词不要写错了,update是人家规定的,不能写成其他值。
                // ishow表示你跟新哪一个值,
                // 将ishow的是跟新为false
                this.$emit('update:ishow',false);//子组件直接修改父组件的值
            }
        }
    }
</script>

我不使用sync可以更改吗?可以的

javascript 复制代码
<template>
  <div>
    请问
    <el-button @click="fatherHander">切换-父按钮</el-button>
    <!-- 缩写的版本 -->
    <!-- <test-com :ishow.sync="flag"></test-com> -->
 
    <!-- 没有被缩写的 -->
    <!-- value 子组件传递过来的参数 -->
    <!-- <test-com :ishow="flag" @update:ishow="value=>flag=value"></test-com> -->
 
    <!-- 与上面的等价哈 -->
    <test-com :ishow="flag" @update:ishow="function(value){  flag=value  }"></test-com>
    <!--  -->
  </div>
</template>
 
<script>
import testcom from "../components/test-com.vue"
  export default {
    data(){
      return{
        flag:true
      }
    },
    components:{
      'test-com':testcom
    },
    methods:{
      fatherHander(){
        this.flag=!this.flag
      }
    },
  }
</script>

注:sync这个语法糖只有在2.3.0这个版本以及上才会有这个方法。

相关推荐
烬羽几秒前
求第 K 大,为什么反而要用最小堆?
javascript·数据结构·算法
jingchao19984 分钟前
Cannot read properties of null (reading ‘insertBefore‘)
前端·javascript·vue.js
计算机魔术师9 分钟前
新文章
前端
爱跳舞的烤冷面11 分钟前
自学嵌入式第N天(Linux篇——文件编程)
java·开发语言·前端
IT_陈寒18 分钟前
Vite的热更新突然失效,原来我忽略了这个配置
前端·人工智能·后端
怪奇云呼军19 分钟前
闪电智能VoiceAgent 如何管理呼入、接听、桥接和挂断状态?
java·前端·网络·数据库·人工智能
云浪22 分钟前
Milvus + RAG 实战:《红楼梦》问答助手
前端·人工智能·后端
梦醒沉醉36 分钟前
2、JavaScript控制流和错误处理
javascript
恋猫de小郭40 分钟前
Dart 3.13 大更新,感觉比 Flutter 更带劲
android·前端·flutter
晓得迷路了41 分钟前
栗子前端技术周刊第 142 期 - DeepSeek Harness、pnpm 12 RC、crypto‑js...
前端·javascript·ai编程