需求:
在父组件的一个事件可以改变子组件中的 openData 的值变为 true。
父级页面:
<template>
<div>
<div @click="changeChild">按钮改变子组件数据</div>
<children ref="childrenDom"></children>
</div>
</template>
<script>
import Childrens from ".../childrens"
export default {
components: {
Childrens
},
methods: {
changeChild() {
this.$refs.childrenDom.openData = true
}
}
}
</script>
注: this.$refs.childrenDom就是指的childrenDom DOM元素
子组件页面:
<script>
export default {
data() {
openData: false
}
}
</script>
完整代码 通过父组件的按钮控制子组件的显示隐藏,对小白来说费脑子啊
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./vue.js"></script>
<style>
.test{
position: absolute;
top: 50px;
width: 150px;
height: 150px;
background-color: aqua;
}
</style>
</head>
<body>
<div id="app">
<baba></baba>
</div>
<!-- 父组件 -->
<template id="baba">
<div class="baba">
<!-- 父组件按钮 -->
<button @click='zx'>父组件的按钮</button>
<!-- 在父组件里嵌套子组件 -->
<son :hehe='name' xixi='456' ref="childrenDom"></son>
</div>
</template>
<!-- 子组件 -->
<template id="son">
<div class="son">
<div class="test" v-show='show'>
子组件的div
通过父组件按钮来控制子组件的显示和隐藏
{{xixi}}
{{hehe}}
</div>
</div>
</template>
<script >
Vue.component('baba',{
template:'#baba',
data(){
return{
name:'hanmeimei'
}
}, methods:{
zx(){
this.$refs.childrenDom.show = !this.$refs.childrenDom.show
}
}
})
Vue.component('son',{
template:'#son',
props:['hehe','xixi'],//用来接收自定义属性
data(){
return{
show:true
}
}
})
let vm=new Vue({
el:'#app',
data:{
show:'true'
},
})
/*
写两个组件是一个嵌套关系
父组件有一个按钮
子组件有一个div
父组件的按钮控制div显示隐藏
props自定义属性 将父亲的数据传给儿子
1.在组件标签上使用自定义属性
2.在组件内部通过props来接收自定义属性
*/
</script>
</body>
</html>