您的位置:首页 > Web前端 > Vue.js

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

2019-06-12 18:30 691 查看

一 . 写组件
新建 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>

完美成功!

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: