在Vue中,组件(Component)用于构建页面结构和UI,而插件(Plugin)用于为应用添加一些额外的功能或工具:
组件(Component)
组件是Vue应用中的基本构建块,用于封装可重用的代码。组件通常包含一个模板、一个脚本和一个样式表,可以独立使用或嵌套在其他组件中。通过组件,可以将页面拆分为更小的、可维护的部分,提高代码的可读性和复用性。
编写组件
编写一个组件,可以有很多方式,我们最常见的就是vue单文件的这种格式,每一个.vue文件我们都可以看成是一个组件
<template>
</template>
<script>
export default{
...
}
</script>
<style>
</style>
我们还可以通过template属性来编写一个组件,如果组件内容多,我们可以在外部定义template组件内容,如果组件内容并不多,我们可直接写在template属性上
<template id="testComponent"> // 组件显示的内容
<div>component!</div>
</template>
Vue.component('componentA',{
template: '#testComponent'
template: `<div>component</div>` // 组件内容少可以通过这种形式
})
组件注册
vue组件注册主要分为全局注册与局部注册
全局注册通过Vue.component方法,第一个参数为组件的名称,第二个参数为传入的配置项
Vue.component('my-component-name', { /* ... */ })
局部注册只需在用到的地方通过components属性注册一个组件
const component1 = {...} // 定义一个组件
export default {
components:{
component1 // 局部注册
}
}
使用组件
使用组件需要在模板中引用组件的标签,如 。
组件的功能通常用于页面结构和交互,通过组合多个组件构建复杂的用户界面。
<div id="app">
<my-component></my-component>
</div>
插件(Plugin)
插件通常用来为 Vue 添加全局功能。插件的功能范围没有严格的限制——一般有下面几种:
添加全局方法或者 property。如:vue-custom-element
添加全局资源:指令/过滤器/过渡等。如 vue-touch
通过全局混入来添加一些组件选项。如 vue-router
添加 Vue 实例方法,通过把它们添加到 Vue.prototype 上实现。
一个库,提供自己的 API,同时提供上面提到的一个或多个功能。如 vue-router
编写插件
vue插件的实现应该暴露一个 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(插件名字,{ /* ... */} )
使用插件
使用插件的功能直接通过全局方法、指令等调用,如 Vue.myGlobalMethod()。
插件的功能在应用中任何地方都可用,包括组件、实例等。
// 注册组件
new Vue({
el: '#app',
components: {
'my-component': MyComponent
}
});
// 使用插件
new Vue({
el: '#app',
mounted() {
// 调用全局方法
Vue.myGlobalMethod();
// 调用实例方法
this.$myMethod();
}
});