需求:
你想写一个组件,想在全部页面都可以这么使用: <el-newbutton>自己封装的按钮</el-newbutton>
做法:
新建一个js文件,import你写好的.vue文件。至于这些文件放哪,全看你项目文件怎么规划的了。
import newbutton1 from './newbutton1'
import newbutton2 from './newbutton2'
export default {
install (Vue) {
Vue.component('el-newbutton1', newbutton)
Vue.component('el-newbutton2', newbutton)
}
}
在man.js处,引入你的.js文件,并且use它,就可以了 很简单
import components from './components/index'
Vue.use(components)
解读:
-
为什么要暴露一个install方法呢?只是因为use方法想在多注册情况下,做的一个应对(接收)。从源码上面看,vue希望你用一个函数来套着这么多公共组件,并且把函数命名为install,仅此而已。
-
为什么里面是Vue.component(‘el-newbutton1’, newbutton)。
其实这里.component很熟悉,就是你平时父组件引入子组件时候,要在父组件进行注册的那个component。 -
vue.use() 方法干嘛用的,他是用来批量注册组件的。如果你只想注册一个组件,你可以在man.js
// 引入全局组件 import toats from './cmcomponents/toats' // 注册为全局组件 Vue.component('toats', toats)
这样你就可以在任何页面使用
<toats></toats>
了,用不上use了