提示:
本文为VUE栏目:VUE学习:Vue CLI
VUE学习:Vue CLI-02————注册全局组件模拟语义化标签
前言
VUECli框架内,Vue项目本身不支持除HTML自带的语义化标签外自定义语义化标签,所以通过注册全局组件的方式,达到语义化标签使用效果。
提示:以下是本篇文章正文内容,下面成功案例可供参考
成功案例
src\components\semanticTag.vue
<template>
<div>
<slot>
</slot>
</div>
</template>
<script>
export default {
name: "SemanticTag"
};
</script>
<style scoped>
</style>
src\plugin\semanticTags.js
import semanticTag from "@/components/semanticTag";
const semanticTagsName=['button-counter', 'tab-container', 'navs', 'tab'];
export default {
install(Vue){
semanticTagsName.map(item => {
Vue.component(item, semanticTag);
});
}
};
main.js
import Components from "@/plugin/semanticTags";
Vue.use(Components);
new Vue({
render: h => h(App)
}).$mount('#app');
插件原理及踩坑
我原本的写法是,在一个js文件中,通过方法注册全局组件:
import Vue from 'vue';
Vue.component('navs', {
template: '<div><slot></slot></div>'
});
然而注册的结果,报错:
You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.
这个错误是说:
项目正在使用 Vue 的运行时构建(runtime-only build),它不包括模板编译器(template compiler)。
在 Vue 2.x 中,存在两种构建:
- 运行时构建(Runtime-only Build):不包含模板编译器,因此不支持
<template>
选项,也不支持Vue.component
的字符串模板。这个构建更小、更快,通常用于生产环境。 - 编译器包含构建(Compiler-included Build):包含模板编译器,因此支持
<template>
选项和字符串模板。这个构建更大,但在开发环境中很有用,因为它允许你使用 Vue 的单文件组件(.vue 文件)。
但是我明明安装vue-template-compiler了。
Vue的官网上说:
如果你恰好使用了 webpack (或在内部使用了 webpack 的 Vue CLI 3+),那么就可以使用 require.context
只全局注册这些非常通用的基础组件。
基础组件,即如果组件只是包裹了一个输入框或按钮之类的元素,是相对通用的。我们有时候会把它们称为基础组件,它们会在各个组件中被频繁的用到。
我姑且算他有理。
多次尝试,确认无法使用template方法注册以后,我决定使用单文件注册。
单文件组件,就不需要在 main.js
中通过 Vue.component
注册组件的字符串模板,可以直接在 .vue
文件中编写组件模板。
完成semanticTag.vue的编写后,定一个数组表明要注册哪些全局组件,然后完成semanticTags.js。
记住全局注册的行为必须在根 Vue 实例 (通过 new Vue
) 创建之前发生。所以main.js中,要先Vue.use(Components);