vue中全局组件的封装与使用

一、写好组件

<template>
  <button class="btn">
    <slot/> <!-- 插槽 -->
  </button>
</template>

<script>
export default {
  // 传入子组件的参数写到props
  props: {
    
  }
}
</script>

<style scoped>
  .btn {
    width: 100px;
    height: 50px;
    color:red;
    border: none;
    font-size: 14px;
  }
</style>

二、子组件添加install方法

创建一个js文件,我将此文件命名为button.js,js文件代码如下:

import ButtonComponent from './Button.vue'

// 添加install方法
const Button = {
  install: function (Vue) {
    Vue.component("Button", ButtonComponent);
  }
}

// 导出
export default Button

三、在 main.js 中引用

import Vue from 'vue'
import App from './App.vue'

import Button from '@/components/Button.js'//引用全局组件Button

Vue.use(Button);//使用全局组件Button

new Vue({
  render: h => h(App),
}).$mount('#app')

四、在页面中使用

<template>
  <div id="app">
    <!-- 使用Button组件 -->
    <Button>全局按钮</Button>
  </div>
</template>

 

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值