携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第18天,点击查看活动详情
一。自定义组件
1.奶茶配料
①。页面布局:
<div class="root">
{{wdactive}}--{{plactive}}--{{tdactive}}
<hr />
{{wdactives}}--{{plactives}}--{{tdactives}}
<!-- 温度 -->
<b-tab
title="温度:"
:list="wdList"
@syncactive="syncwd"
:active="wdactive"
></b-tab>
<!-- 配料 -->
<b-tab
title="配料:"
:list="plList"
@syncactive="syncpl"
:active="plactive"
></b-tab>
<!-- 甜度 -->
<b-tab
title="甜度:"
:list="tdList"
@syncactive="synctd"
:active="tdactive"
></b-tab>
</div>
②。vue组件
自定义全局组件
Vue.component("b-tab", {
// @click="myactive=index" 点击的时候让高亮索引等于点击的索引
template: `
<div class="tab">
<div>{{title}}</div>
<ul>
<li
v-for="(item,index) in list"
:key="index"
@click="myactive=index"
:class="{active:myactive==index}"
>
{{item}}
</li>
</ul>
</div>
`,
props: {
title: {
type: String,
},
list: {
type: Array,
},
active: {
type: Number,
},
},
data() {
return {
因为active的值是会变化的,这个值是通过父组件..active变化的,不属于自己的值,不可以改变,所以需要定一个属与自己的属性接收
myactive: this.active,
};
},
监听myactive,当myactive的值变化的时候会返回两个值,一个旧值,一个新值,但这里不需要旧值,只需要新值,所以只接收新值即可
this.$emit("syncactive", nval);通过触发自定义事件,来给触发监听事件, 第一个参数是事件名,第二个参数是监听的值
watch: {
myactive(nval) {
console.log(nval);
// 通过触发自定义事件,来给触发监听事件,
// 第一个参数是事件名,第二个参数是监听的值
this.$emit("syncactive", nval);
},
},
});
new Vue({
el: ".root",
data: {
//用来页面展示返回的值
wdactives: "",
plactives: "",
tdactives: "",
// 温度高亮索引
wdactive: 0,
// 温度数组
wdList: ["加冰", "少冰", "去冰", "常温"],
// 配料高亮索引
plactive: 0,
// 配料数组
plList: ["红豆", "椰果", "珍珠", "波霸"],
// 甜度高亮索引
tdactive: 0,
// 甜度
tdList: ["全塘", "半塘", "上塘", "无糖"],
},
methods: {
e是监听事件的返回值,
syncwd(e) {
console.log(e); //高亮索引下标
this.wdactive = e; //点击的时候返回值也在变化
this.wdactives = this.wdList[e];//点击的时候返回值也在变化
},
syncpl(e) {
this.plactive = e;
this.plactives = this.plList[e];
},
synctd(e) {
this.tdactive = e;
this.tdactives = this.tdList[e];
},
},
mounted() {
this.wdactives = this.wdList[0];
this.plactives = this.plList[0];
this.tdactives = this.tdList[0];
},
});
页面展示效果: