Vue组件间通信的方式有N多种了,但无非是父子组件间通信,兄弟组件间通信,跨级组件间通信。
父子间通信:
1、 父传子(props) 今天介绍
2、 子传父($emit)
其他组件间通信:
Vuex 偷个懒,其实有很多,哈哈~
直接上代码:
父组件.vue
<template>
<view>
<div class="tab">
<view
v-for="(tab,index) in tabs"
:key="index"
class=tchild
:class="{active:curtab == index}" //active为选中状态
@click="toggletab(index)"
>{{tab.title}}
</view>
</div>
<div class="tbox">
<keep-alive> //添加缓存,下次打开页面时会保留上次浏览时的状态
<tchild :list="a"></tchild>//list为子组件props接收的值,a为父组件要传的值,不要搞反
</keep-alive>
</div>
</view>
</template>
<script>
import tchild from './tabchild.vue'
export default{
data(){
return{
tabs:[
{id:0,title:'月度',isselect:true},
{id:1,title:'季度',isselect:false},
{id:2,title:'半年',isselect2:false},
{id:3,title:'整年',isselect3:false},
],
list0:[
{count:'10M/月',price:'售价:10元(原价:30元)'},
{count:'11M/月',price:'售价:11元(原价:30元)'},
{count:'12M/月',price:'售价:11元(原价:30元)'},
{count:'13M/月',price:'售价:12元(原价:30元)'},
],
list1:[
{count:'20M/月',price:'售价:27元(原价:30元)'},
{count:'21M/月',price:'售价:28元(原价:30元)'},
{count:'22M/月',price:'售价:29元(原价:30元)'},
{count:'23M/月',price:'售价:23元(原价:30元)'},
],
list2:[
{count:'30M/月',price:'售价:37元(原价:30元)'},
{count:'31M/月',price:'售价:38元(原价:30元)'},
{count:'32M/月',price:'售价:39元(原价:30元)'},
{count:'33M/月',price:'售价:33元(原价:30元)'},
],
list3:[
{count:'40M/月',price:'售价:47元(原价:30元)'},
{count:'41M/月',price:'售价:48元(原价:30元)'},
{count:'42M/月',price:'售价:49元(原价:30元)'},
{count:'43M/月',price:'售价:43元(原价:30元)'},
],
curtab:0,
a:[], //要传给子组件的值
}
},
components:{
tchild,
},
methods:{
toggletab(index){ //选项卡切换
this.curtab=index;
if(index==0){
this.a = this.list0;
}
if(index==1){
this.a = this.list1;
}
if(index==2){
this.a = this.list2;
}
if(index==3){
this.a = this.list3;
} //有点繁琐,欢迎提出更好的方法
},
},
created() {
this.a=this.list0;
}
}
</script>
<style>
</style>
子组件 tabchild.vue
<template>
<view>
<div class="box" >
<div
class="child"
:class="{choose:index==n}" //choose为选中状态
v-for='(item,index) in lists'
:key='index'
@click="changeindex(index)"
>
<div class="cn">{{item.count}}</div>
<div class="price">{{item.price}}</div>
<span></span>
</div>
</div>
</view>
</template>
<script>
export default {
name:'tchild', //此处随意
props:{
list:Array //可简写为 props:['list']
},
data(){
return{
n:0,
lists:'',
}
},
methods:{
changeindex(index){ //单选切换
this.n=index;
}
},
created(){
this.lists=this.list; //第一次进入页面时防止值为空
},
watch:{
list(val){ //重点:当父组件传来的list发生改变时,触发watch,val为更改后的新list值,成就子组件的lists动态更改
this.lists=val; //如果值的层数较深,需要进行遍历,可添加deep:true;
}
},
}
</script>
<style>
</style>
还是比较简单的,嘿嘿
坚持更新,望各位学有所成!