vue2注册实现
vue2 注册实现
在 Vue2 中,注册通常指全局或局部注册组件、指令、过滤器等。以下是常见的注册方式:
全局组件注册
通过 Vue.component 方法全局注册组件,所有 Vue 实例均可使用。
// 注册全局组件
Vue.component('my-component', {
template: '<div>全局组件内容</div>'
});
// 使用
new Vue({
el: '#app',
template: '<my-component></my-component>'
});
局部组件注册
在组件选项中通过 components 属性注册局部组件,仅当前组件可用。
const ChildComponent = {
template: '<div>子组件内容</div>'
};
new Vue({
el: '#app',
components: {
'child-component': ChildComponent
},
template: '<child-component></child-component>'
});
全局指令注册
通过 Vue.directive 注册自定义指令。
// 注册全局指令
Vue.directive('focus', {
inserted: function (el) {
el.focus();
}
});
// 使用
new Vue({
el: '#app',
template: '<input v-focus>'
});
局部指令注册
在组件选项中通过 directives 属性注册局部指令。
new Vue({
el: '#app',
directives: {
'highlight': {
bind(el, binding) {
el.style.backgroundColor = binding.value || 'yellow';
}
}
},
template: '<div v-highlight>高亮内容</div>'
});
全局过滤器注册
通过 Vue.filter 注册全局过滤器。
// 注册全局过滤器
Vue.filter('capitalize', function (value) {
if (!value) return '';
return value.toString().charAt(0).toUpperCase() + value.slice(1);
});
// 使用
new Vue({
el: '#app',
template: '<div>{{ "hello" | capitalize }}</div>'
});
局部过滤器注册
在组件选项中通过 filters 属性注册局部过滤器。
new Vue({
el: '#app',
filters: {
reverse: function (value) {
return value.split('').reverse().join('');
}
},
template: '<div>{{ "vue" | reverse }}</div>'
});
插件注册
通过 Vue.use 注册插件。

// 定义插件
const MyPlugin = {
install(Vue) {
Vue.prototype.$myMethod = function () {
console.log('插件方法');
};
}
};
// 注册插件
Vue.use(MyPlugin);
// 使用
new Vue({
el: '#app',
created() {
this.$myMethod(); // 输出: "插件方法"
}
});
以上方法覆盖了 Vue2 中常见的注册场景,可根据需求选择全局或局部注册方式。






