传值的几种方式
子父(向上)传值教程
组件之间数据的传值均是单向数据流。
初始代码:(现在没有向上传值)
/*==========================html=======================================*/
<div id="root">
<input type="button" @click="isShow = !isShow" value="显示与隐藏">
<wrap v-show="isShow" :change-is-show="changeIsShow"></wrap>
</div>
/*==========================js=======================================*/
new Vue({
el:"#root",
data: {
isShow: true
},
components:{
wrap:{
props:["changeIsShow"],
template:`
<div style="width:200px;height:200px;background:red;">
我是一个名字wrap的组件
</div>
`
}
}
})
效果:(可以点击显示隐藏按钮是下面红色区域消失显示)
现在我希望在 红色区域添加一个按钮,实现它自己的隐藏
- 用于决定这个区域是否隐藏的就用到了 父级中的决定显示隐藏的数据(isShow)
- 只要我能够在我的子组件中修改我父及的 isShow 就可以了
- 这就是子父(向上)之间的传值
/*-----------------------html---------------------------------*/
<div id="root">
<input type="button" @click="isShow = !isShow" value="显示与隐藏">
<wrap v-show="isShow" :change-is-show="changeIsShow"></wrap> //使用 changeIsShow 方法
</div>
/*-----------------------js---------------------------------*/
new Vue({
el:"#root",
data: {
isShow: true
},
methods:{ //我新建了一个方法,
changeIsShow(bol){
this.isShow = bol;
}
},
components:{
wrap:{
props:["changeIsShow"],
template:`
<div style="width:200px;height:200px;background:red;">
<input type="button" @click="changeIsShow(false)" value="隐藏">
我是一个名字wrap的组件
</div>
`
}
}
})
图解