vue插件初探

vue插件很多,也有官方插件,vue插件定位并不死板,按照官方说法是如此的

先上vue插件文档,不熟悉的可自行查阅先vue插件官方文档

插件一般有一下几种(来自官方文档)

1.添加全局方法或者属性

2.添加全局资源:指令/过滤器/过渡等

3.通过全局 mixin 方法添加一些组件选项

4.添加 Vue 实例方法,通过把它们添加到 Vue.prototype 上实现

5.一个库,提供自己的 API,同时提供上面提到的一个或多个功能

接下来先说一下场景,有时候我们有很多组件使用频率很高需要全局注册

Vue.component('pluginName',plugin);		//main.js下可全局注册

上面可行,但是当需要全局注册组件比较多时会把main.js搞得比较混乱,不太好管理

这时可以用vue插件来做,在main.js里引入使用即可

下面说下插件开发流程,面向有模板的情况下

先声明一个对象并将其导出

//引入模板
import ComponentTest from './components/componentTest'

const component = [
	ComponentTest
];
//声明对象并将其导出
//对象里必须包含install方法
//此方法供Vue.use()使用引入
export default {
	install(Vue, options) {
		component.forEach(component => {
			//注册组件
			Vue.component(component.name, component);
		})
	}
}

引入的模板如下

<template>
	<span>这里是组件A</span>
</template>

<script>
export default {
	name: 'ComponentTest'
}
</script>

以上两者具备就可以在main.js里使用了

import Vue from 'vue'
import App from './App'
import router from './router'
import MyPlugin from './myPlugin'	//引入插件

Vue.config.productionTip = false
Vue.use(MyPlugin)					//使用插件

new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

到这里,在MyPlugin里全局注册的CompentTest就可以在全局使用该组件了

<component-test></component-test>

以上是一个组件库的初始形态,按照这样的初始框架可以完成自己的组件库

当然复杂的组件库还有更多东西要用到

实际上element-ui的组件库最外层的架子就是如此,有兴趣的可以拜读一下

猜你喜欢

转载自blog.csdn.net/garrettzxd/article/details/80752695