一、基本概念
-
组件:组件就是把图形、非图形的各种逻辑均抽象为一个统一的概念(组件)来实现开发的模式,在 Vue 中每一个 .vue 结尾的文件都可以视为一个组件
-
插件:插件通常用来为 Vue 构造函数添加全局功能,比如 vue-router、VueX 都是插件
二、区别
编写组件
// vue 文件标准格式
<template>
</template>
<script>
export default{}
</script>
<style>
</style>
// 通过 template 属性编写组件
<template id="testComponent"> // 组件显示的内容
<div>component!</div>
</template>
Vue.component('componentA',{
template: '#testComponent'
template: `<div>component</div>` // 组件内容少可以通过这种形式
})
// 注册全局组件
Vue.component('my-component-name', { /* ... */ })
// 注册局部组件
export default {
components:{
component1 // 局部注册
}
}
编写插件
// 插件需要暴露一个 install 方法。这个方法的第一个参数是 Vue 构造函数,第二个参数是一个可选的选项对象
MyPlugin.install = function (Vue, options) {
// 1. 添加全局方法或 property
Vue.myGlobalMethod = function () {
// 逻辑...
}
// 2. 添加全局资源
Vue.directive('my-directive', {
bind (el, binding, vnode, oldVnode) {
// 逻辑...
}
...
})
// 3. 注入组件选项
Vue.mixin({
created: function () {
// 逻辑...
}
...
})
// 4. 添加实例方法
Vue.prototype.$myMethod = function (methodOptions) {
// 逻辑...
}
}
// 注册插件,Vue.use 会自动阻止多次注册相同插件,只会注册一次
Vue.use(插件名字,{ /* ... */} )