实现效果:
父组件的一个按钮控制子组件显示,子组件内部有一个按钮,控制自己隐藏,效果如下:
法一:子组件中通过$emit一个事件告诉父组件要修改的值,然后在父组件里修改show的值,子组件的值就会自动更新了
父组件:
<template>
<div>
<input type="button"
value="我是父组件中的按钮"
@click="show">
<child v-show="isShow" @changeIsShow="hideChild" />
</div>
</template>
<script>
import child from "./child.vue"
export default {
data() {
return {
isShow:false
}
},
components:{
child
},
methods:{
show(){
this.isShow = true;
},
hideChild(data) {
this.isShow = data;
}
}
}
</script>
子组件:
<template>
<div class="box">
我是一个子组件!
<button @click="hide">点我隐藏</button>
</div>
</template>
<script>
export default {
data() {
return {
}
},
methods: {
hide() {
this.$emit('changeIsShow', false);
}
}
}
</script>
<style scoped>
.box {
height: 100px;
width: 100px;
background: rgb(248, 162, 162);
}
</style>
法二:.sync(vue3已弃用,合在v-model中)
父组件:
<template>
<div>
<input type="button"
value="我是父组件中的按钮"
@click="show">
<!-- 这里有修改 -->
<child v-show="isShow" :changeIsShow.sync="isShow" />
</div>
</template>
<script>
import child from "./child.vue"
export default {
data() {
return {
isShow:false
}
},
components:{
child
},
methods:{
show(){
this.isShow = true;
}
}
}
</script>
子组件:
<template>
<div class="box">
我是一个子组件!
<button @click="hide">点我隐藏</button>
</div>
</template>
<script>
export default {
data() {
return {
}
},
methods: {
hide() {
this.$emit('changeIsShow', false);
}
}
}
</script>
<style scoped>
.box {
height: 100px;
width: 100px;
background: rgb(248, 162, 162);
}
</style>
sync 就是一个语法糖,
:changeIsShow.sync="isShow"
等价于
v-on:update:changeIsShow="data => isShow = data"
法三:v-model
父组件:
<template>
<div>
<input type="button"
value="我是父组件中的按钮"
@click="show">
<!-- 这里有修改 -->
<child v-show="isShow" v-model="isShow" />
</div>
</template>
<script>
import child from "./child.vue"
export default {
data() {
return {
isShow:false
}
},
components:{
child
},
methods:{
show(){
this.isShow = true;
}
}
}
</script>
子组件:
<template>
<div class="box">
我是一个子组件!{{modelValue}}
<button @click="hide">点我隐藏</button>
</div>
</template>
<script>
export default {
data() {
return {
}
},
// 这里有修改
props: {
modelValue: { // vue2是value,vue3是modelValue
type: Boolean,
required: true
},
},
methods: {
hide() {
// 这里有修改
this.$emit('update:modelValue', false); // vue3
// this.$emit('input', false); vue2
}
}
}
</script>
<style scoped>
.box {
height: 100px;
width: 100px;
background: rgb(248, 162, 162);
}
</style>
也可以不使用 modelValue,比如换成value 只需要修改(vue3):
<child v-show="isShow" v-model:value="isShow" />
子组件中修改成:
props: {
value: {
type: Boolean,
required: true
},
},
methods: {
hide() {
this.$emit('update:value', false);
}
}
版权声明:本文为DZY_12原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。