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这个版本以及上才会有这个方法。

相关推荐
暴走的小呆2 分钟前
为什么react要从顶层更新
前端
Fisschl13 分钟前
在 Vue 中使用 remark 渲染 markdown
vue.js
仰望星空的小猴子13 分钟前
React18和React19新特性
前端
小码哥_常15 分钟前
Android新航标:Navigation 3为何成为变革先锋?
前端
SuperEugene16 分钟前
Vue状态管理扫盲篇:状态管理中的常见坑 | 循环依赖、状态污染与调试技巧
前端·vue.js·面试
骑着小黑马17 分钟前
从 Electron 到 Tauri 2:我用 3.5MB 做了个音乐播放器
前端·vue.js·typescript
进击的尘埃17 分钟前
前端大文件上传全方案:切片、秒传、断点续传与 Worker 并行 Hash 计算实践
javascript
aykon17 分钟前
DataSource详解以及优势
前端
Mintopia17 分钟前
戴了 30 天智能手环后,我才发现自己一直低估了“睡眠”
前端
leolee1818 分钟前
react redux 简单使用
前端·react.js·redux