Vue 的组件作用域都是孤立的,不允许在子组件的模板内直接引用父组件的数据。必须使用特定的方法才能实现组件之间的数据传递。
一、父组件向子组件传递数据
在 Vue 中,可以使用 props 向子组件传递数据。
子组件部分:
如果需要从父组件获取 username 的值,就需要
props:{
username:{
type:String
}
}
示例代码
<template>
<div class="child01">
my name is {{username}}
</div>
</template>
<script>
export default {
name: 'child01',
props:{
username:{
type:String
}
}
}
</script>
在 props 中添加了元素之后,就不需要在 data 中再添加变量啦。
父组件部分:
示例代码
<template>
<div class="child01">
<child-box :username="zuobaiquan"></child-box>
</div>
</template>
<script>
import childBox from './child.vue'
export default {
name: 'child01',
data () {
return {
zuobaiquan:'zuobaiquan'
}
},
components:{
'child-box':childBox
}
}
</script>
二、子组件向父组件传递数据
一般情况下,子组件主要通过事件传递数据给父组件
子组件部分:
示例代码
<template>
<ul class="tab-list">
<li class="tab-li"
v-for="(item, index) in tabItem"
v-html="item"
:class="{active: index === actIndex}"
@click="handelSwitch(index)"
>
</li>
</ul>
</template>
<script>
export default {
name: 'child02',
data(){
return {
tabItem:['选项一','选项二','选项三'],
actIndex:0
}
},
methods:{
handelSwitch(index){
this.actIndex=index;
this.$emit("transferTabIndex",this.actIndex)
}
}
}
</script>
这是选项卡子组件,当tabItem的index值发生变化的时候,将 对应的tab的索引index传递给父组件
首先声明一个了方法 handelSwitch,通过点击事件click来调用 handelSwitch,在 handelSwitch方法中,使用了 $emit 来遍历 transferTabIndex事件,并传递 this.actIndex,
其中 transferTabIndex是一个自定义的事件,功能类似于一个中转站,可以把this.actIndex通过这个事件传递给父组件
父组件部分:
在父组件parent.vue 中,声明了一个方法 getTabIndex,用 transferTabIndex事件调用 handelSwitch方法,获取到从子组件传递过来的参数 this.actIndex,传递过来的this.actIndex 可以实现 选项卡的div模块的显示与隐藏。
注意:
如果无需传递参数,直接写成 this.$emit(方法名);
如果是一个参数,直接以追加参数即可;
如果是多个参数,直接对象形式或者数组格式传递。
示例代码
<template>
<div class="child02">
<child-box @transferTabIndex="getTabIndex"></child-box>
<div v-show="showIndex==0">我的选项卡1</div>
<div v-show="showIndex==1">我的选项卡2</div>
<div v-show="showIndex==2">我的选项卡3</div>
</div>
</template>
<script>
import childBox from './child.vue'
export default {
name: 'child02',
data () {
return {
showIndex:0
}
},
components:{
'child-box':childBox
},
methods:{
getTabIndex(index){
this.showIndex=index;
}
}
}
</script>
三、父组件事件触发子组件
现在有这么一个需求,在父组件的某一个地方,点击 可以切换tab,这个需求也得益于公司的一个项目
https://emdatahkush5.eastmoney.com/view/financeCalendar.html#/
如图,点击 【全部】选项卡 下的 “查看更多”按钮切换到 其他的tab 页。
此时的做法是
1、父组件的button元素绑定click事件,该事件指向 tabToThree 方法
2、在 组件中 给父组件注册一个 ref="childTab" 。
3、父组件的 childTab 的方法在处理时,使用 $refs.childTab 把事件传递给子组件的 handelSwitch 方法,同时携带着父组件中的参数 index
4、子组件接收到父组件的事件后,调用 handelSwitch 方法,把接收到的 index 放到 actIndex中,触发 tab选项卡的同步变化。
源码地址https://github.com/zuobaiquan/vue/tree/master/vueExercise/vue-component