创建组件,通过组件按钮实现点击事件。
父组件按钮点击后出现红色框,在通过子组件中创建的按钮点击关闭。这里需要父子通讯来进行。
先使用子传父,父组件调用子组件的标签上加入v-show来控制显示与隐藏。先设置一个data的值为false,最后通过父组件按钮控制data中的值改变,实现子组件的显示域=与隐藏。
点击子组件按钮隐藏需要使用$emit派发事件控制,并将相关样式设置好。
以下是子组件代码
<template>
<div class="vs">
<button type="button" @click="changeShow">点我消失</button>
</div>
</template>
<script>
export default {
name: 'VueSync',
methods: {
changeShow() {
this.$emit('update:isShow', false)
//这里派发的名字有update是官网的一个要求,冒号加上也行,派发时的需要相同
}
}
}
</script>
<style>
.vs {
width: 500px;
height: 500px;
background-color: #f00;
}
</style>
父组件调用后使用派发的事件控制父组件中的data的值,间接实现控制。并且可以进行相关简写。
<template>
<div id="app">
<!-- <img alt="Vue logo" src="./assets/logo.png"> -->
<!-- 3 -->
<button type="button" @click="handleClick">我是父组件的按钮</button>
<!-- <VueSync v-show="isShow" @update:isShow="noshow"></VueSync> -->
<!-- 第二种,直接写成函数 -->
<!-- <VueSync v-show="isShow" @update:isShow="function(bol){isShow = bol}"></VueSync> -->
<!-- 第三种 箭头函数 data中的不能写成箭头函数-->
<!-- <VueSync v-show="isShow" @update:isShow="bol=>isShow = bol"></VueSync> -->
<!-- 第四种语法糖,sync @需要换成: v-on换成v-bind绑定 vue3中取消了,过滤器也取消了 -->
<VueSync v-show="isShow" :isShow.sync="isShow"></VueSync>
</div>
</template>
<script>
import VueSync from '@/components/VueSync.vue' //1
export default {
name: 'App',
components: {
VueSync ,//2
//all
},
data() {
return {
isShow: false
}
},
methods: {
handleClick() {
this.isShow = !this.isShow
},
noshow(bol) {
this.isShow = bol
}
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>