在vue中全局組件的封裝與使用

一 . 寫組件
新建 button.vue 組件

 <template>
  <button>
    <slot> <slot/>         <!-- 插槽 -->
  </button>
</template>
 
<script>
export default {
  // 傳入子組件的參數寫到props
  props: {
    num: {
      type : Number
    }
  }
}
</script>

二 . 在子組件中添加install方法
創建一個index.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 index from './index.js'//引用全局組件index
 
Vue.use(index);//使用全局組件index
 
new Vue({
  render: h => h(App),
}).$mount('#app')

四、在頁面中使用

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

完美成功!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章