vue2二次组件封装

vue2二次组件封装

我这里使用的UI组件库是antd2,对于二次组件封装需要解决的问题其实就是如何将原有组件的属性、事件、方法、插槽传递过去,直接看代码吧。

1、安装vue2

1.安装vue2脚手架

npm install -g @vue/cli-init

2.安装vue2项目

npm create vue@2.x
2、安装UI库(Antd2)

注意:vue2封装和vue3封装是不同的

npm i --save ant-design-vue@1.x

查看一下我的安装情况:
在这里插入图片描述

3、上代码

自定义组件MyButton

<template>
    <div>
        <a-button v-bind="$attrs" v-on="$listeners">
            <template v-for="(val,key) in $slots">
                <slot :name="key"></slot>
            </template>
        </a-button>
        <div class="btip">
            <slot name="btip" :msg="tipContent"></slot>
        </div>
        
    </div>
</template>

<script>
    export default {
        name:'MyButton',
        data(){
            return{
                tipContent:'小提示:'
            }
        },
        created(){
            console.log('$attrs',this.$attrs)
            console.log('$listeners',this.$listeners)
            console.log('$slots',this.$slots)
        }
    }
</script>

<style scoped>
.btip{
    border:1px solid aquamarine;
    color: red;
    text-align: center;
}
</style>

全局注册组件main.js

import Vue from 'vue'
import App from './App.vue'
import Antd from 'ant-design-vue';
import 'ant-design-vue/dist/antd.css';
import Mybutton from "./components/MyButton.vue";

import './assets/main.css'
Vue.config.productionTip = false;
//全局注册antd
Vue.use(Antd);
//全局注册自定义组件
console.log(Mybutton.name)
Vue.component(Mybutton.name,Mybutton)
new Vue({
  render: (h) => h(App)
}).$mount('#app')

使用组件App.vue

<script setup>
</script>

<template>
  <div id="app">
    <my-button type="primary" danger>
      测试按钮
      <template #btip="row">
        {{row.msg}}AAA
      </template>
    </my-button>
  </div>
</template>

<style scoped>

</style>

效果:
在这里插入图片描述
看看控制台都打印出了什么?
在这里插入图片描述
这就是vue2版本的二次封装,yyds

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值