当前位置: 首页> 汽车> 时评 > 【Vue】sync修饰符

【Vue】sync修饰符

时间:2025/7/11 0:28:38来源:https://blog.csdn.net/qq_39921135/article/details/139486262 浏览次数: 0次

文章目录

  • 一、介绍
  • 二、语法
  • 三、代码示例

一、介绍

作用:可以实现 子组件父组件数据双向绑定,简化代码

简单理解:子组件可以修改父组件传过来的props值

特点:prop属性名,可以自定义,非固定为value

但是.sync没有v-model方便,所以当属性名确定为value,即表单元素的时候,就使用v-model

**场景 ** 封装弹框类的基础组件, visible属性 true显示 false隐藏

本质 .sync修饰符 就是 :属性名@update:属性名 合写


二、语法

父组件

// .sync写法
<BaseDialog :visible.sync="isShow" />
--------------------------------------
// 完整写法
<BaseDialog :visible="isShow" @update:visible="isShow = $event" 
/>

子组件

props: {visible: Boolean
},this.$emit('update:visible', false)

三、代码示例

App.vue

<template><div class="app"><button @click="openDialog">退出按钮</button><!-- isShow.sync  => :isShow="isShow" @update:isShow="isShow=$event" --><BaseDialog :isShow.sync="isShow"></BaseDialog></div>
</template><script>
import BaseDialog from './components/BaseDialog.vue'
export default {data() {return {isShow: false,}},methods: {openDialog() {this.isShow = true// console.log(document.querySelectorAll('.box')); },},components: {BaseDialog,},
}
</script><style>
</style>

BaseDialog.vue

<template><div class="base-dialog-wrap" v-show="isShow"><div class="base-dialog"><div class="title"><h3>温馨提示:</h3><button class="close" @click="closeDialog">x</button></div><div class="content"><p>你确认要退出本系统么?</p></div><div class="footer"><button>确认</button><button>取消</button></div></div></div>
</template><script>
export default {props: {isShow: Boolean,},methods:{closeDialog(){this.$emit('update:isShow',false)}}
}
</script><style scoped>
.base-dialog-wrap {width: 300px;height: 200px;box-shadow: 2px 2px 2px 2px #ccc;position: fixed;left: 50%;top: 50%;transform: translate(-50%, -50%);padding: 0 10px;
}
.base-dialog .title {display: flex;justify-content: space-between;align-items: center;border-bottom: 2px solid #000;
}
.base-dialog .content {margin-top: 38px;
}
.base-dialog .title .close {width: 20px;height: 20px;cursor: pointer;line-height: 10px;
}
.footer {display: flex;justify-content: flex-end;margin-top: 26px;
}
.footer button {width: 80px;height: 40px;
}
.footer button:nth-child(1) {margin-right: 10px;cursor: pointer;
}
</style>
关键字:【Vue】sync修饰符

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: