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>

猜你喜欢

转载自blog.csdn.net/jiangwei1994/article/details/88863154
今日推荐