vue 组件封装中,使用model 配合.sync 修饰符实现联动实现子组件数据改变同步修改父组件
chid.vue
<template>
<div>
<el-button @click="showChange">button</el-button>
<div v-show="show">{{ name }}</div>
</div>
</template>
<script>
export default {
props: {
name: {
type: String,
default: "测试"
},
show: {
type: Boolean,
default: false
}
},
model: {
prop: "show",
event: "show-change"
},
methods: {
showChange() {
// update:show 配合update 加上 model 中的 prop 通知 使用
this.$emit("update:show", !this.show);
this.$emit("show-change", this.show);
}
}
};
</script>
<style lang="scss" scoped></style>
parent.vue
<template>
<!-- .sync 需要配合 sync修饰符才能使用 -->
<child :show.sync="show"></child>
</template>
<script>
import child from "./child.vue"
export default {
components: { child },
data() {
return {
show: false,
}
}
}
</script>