实现v-model封装组件,并挂载全局
核心:监听value的变化,利用input事件传递给父组件,实现传值用v-model
组件:
<template>
<div class="head-radio">
<div
v-for="(v, k) in list"
:key="k"
:class="v === myValue ? 'active' : ''"
>
<span>{{ v }}</span
><i v-show="v === myValue"></i>
</div>
</div>
</template>
<script>
export default {
name: 'HeadRadio',
props: {
list: {
type: Array,
default: () => []
},
value: {
type: String,
default: ''
}
},
data() {
return {
myValue: this.value
};
},
watch: {
value(newValue) {
this.myValue = newValue;
},
myValue(newValue) {
this.$emit('input', newValue);
}
},
methods: {
}
};
</script>
<style lang="less">
.head-radio {
font-size: 16px;
display: flex;
height: 40px;
background: #f5f8f8;
border-radius: 5px;
line-height: 36px;
& > div {
cursor: pointer;
text-align: center;
flex: 1;
color: #222;
& + div {
position: relative;
&::before {
content: '';
display: inline-block;
position: absolute;
width: 1px;
height: 20px;
background-color: #dce5e5;
left: 0;
top: 10px;
}
}
&.active {
color: @key-color;
font-weight: bold;
position: relative;
border-bottom: 3px solid #4cc9da;
i {
display: block;
width: 16px;
height: 10px;
background: url(./imgs/tab_select.png) no-repeat center;
background-size: 100% 100%;
position: absolute;
bottom: -3px;
left: 50%;
transform: translateX(-50%);
}
}
&:last-child {
margin-right: 0;
}
}
}
</style>
全局引入:新建一个js文件在main.js文件中引入
import Vue from 'vue';
import HeadRadio from './head-radio';
const components = [HeadRadio];
const install = function (Vue) {
components.forEach((component) => {
Vue.component(component.name, component);
});
};
install(Vue);
使用
<HeadRadio :list="tabs" v-model="tabName" />
<script>
export default {
data(){
tabs: ['tab1', 'tab2'],
tabName: 'tab1',
}
}
</script>