vue 实现v-model封装组件,并挂载全局

10 篇文章 0 订阅

实现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;
    // margin-right: 15px;
    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>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值