Vue 插件与组件:从全局注入到局部使用的核心区别(Vue2/Vue3 案例)
·
Vue 插件与组件的核心区别
插件(Plugin)
插件是用于增强 Vue 全局功能的模块,通常通过 Vue.use() 安装。插件可以:
- 添加全局方法或属性(如
Vue.prototype.$axios) - 注入全局资源(如自定义指令、过滤器)
- 通过全局混入添加组件选项
- 提供全局工具库(如 Vue Router、Vuex)
组件(Component)
组件是独立的 UI 或功能单元,通过局部或全局注册复用。核心特点:
- 封装模板、逻辑和样式
- 通过父子通信(props/events)或状态管理共享数据
- 支持局部注册(单文件组件)或全局注册(
Vue.component())
全局注入与局部使用的差异
全局注入(插件典型场景)
// Vue2 插件示例:全局 axios 注入
const plugin = {
install(Vue) {
Vue.prototype.$axios = axios;
}
};
Vue.use(plugin);
// 任意组件内直接使用
this.$axios.get('/api');
局部使用(组件典型场景)
// Vue3 局部组件注册
import LocalComponent from './LocalComponent.vue';
export default {
components: { LocalComponent }
};
// 模板中通过标签调用
<local-component />
Vue2 与 Vue3 的关键案例对比
Vue2 插件实现
// 自定义指令插件
const directivePlugin = {
install(Vue) {
Vue.directive('focus', {
inserted(el) {
el.focus();
}
});
}
};
Vue.use(directivePlugin);
// 全局使用
<input v-focus />
Vue3 插件实现
// 组合式 API 插件
const plugin = {
install(app) {
app.config.globalProperties.$log = (msg) => console.log(msg);
}
};
app.use(plugin);
// 组件内调用
const { proxy } = getCurrentInstance();
proxy.$log('debug');
Vue3 局部组件与 Composition API
// 局部组件 + provide/inject
// 父组件
import { provide } from 'vue';
import ChildComponent from './Child.vue';
setup() {
provide('theme', 'dark');
}
// 子组件
import { inject } from 'vue';
setup() {
const theme = inject('theme');
return { theme };
}
选择建议
-
插件适用场景
- 需要全局扩展功能(如路由、状态管理)
- 跨组件共享工具方法
- 修改 Vue 本身的行为(如自定义渲染器)
-
组件适用场景
- 复用 UI 元素或独立功能模块
- 需要隔离作用域(避免全局污染)
- 动态按需加载(通过异步组件)
更多推荐
所有评论(0)