版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
一 . 写组件
新建 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>
完美成功!