Tui组件,已发布npm,可以如下方式引入
// 先安装
npm i @wocwin/t-ui
// 在main.js中按下引入
import Tui from '@wocwin/t-ui'
Vue.use(Tui)
一、个人对组件注册的理解(仅仅是个人理解)
组件注册分两种:全局注册和局部注册(即单个页面引入注册);就我个人:通常我会把基础组件(整个项目超过60%以上的页面都会使用的组件——通常设定为基础组件)全局注册;而业务组件(指定针对某一个页面而封装的组件,里面存着单个页面的业务逻辑——通常设定为业务组件)就是单个页面引入注册
二、全局注册方法
1、第一种(传统方式)
// 在main.js中如下配置
import XXX from "路径"
Vue.component("名字要是字符串的格式",XXX)
2、第二种利用webpack的方式(require.context)
注意:以下这种方式,必须每个以.vue文件都需要设置name属性
import Vue from 'vue'
// 全局自动注册baseComponents下的基础组件
const requireComponent = require.context('./baseComponents', true, /\.vue$/)
// 找到组件文件夹下以.vue命名的文件,如果文件名为index,那么取组件中的name作为注册的组件名
requireComponent.keys().forEach(filePath => {
const componentConfig = requireComponent(filePath)
const fileName = validateFileName(filePath)
const componentName = fileName.toLowerCase() === 'index'
? capitalizeFirstLetter(componentConfig.default.name)
: fileName
Vue.component(componentName, componentConfig.default || componentConfig)
})
// 首字母大写
function capitalizeFirstLetter (str) {
return str && str.charAt(0).toUpperCase() + str.slice(1)
}
// 对符合'xx/xx.vue'组件格式的组件取组件名
function validateFileName (str) {
return /^\S+\.vue$/.test(str) &&
str.replace(/^\S+\/(\w+)\.vue$/, (rs, $1) => capitalizeFirstLetter($1))
}
然后在main.js如下注册(即可全局使用)
import './components/index.js' // 全局基础组件注入
3、第三种(用install,就以我封装的Tui为例)Tui gitHub组件地址
1、找到 packages下的index.js(以下是关键代码)
// 定义 install 方法,接收 Vue 作为参数。如果使用 use 注册插件,则所有的组件都将被注册
const install = function (Vue) {
// 判断是否安装
if (install.installed) return
install.installed = true
// 遍历注册全局组件
components.map(component => Vue.component(component.name, component))
}
// 判断是否是直接引入文件
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue)
}
export default {
...components, // 按需引入
// 导出的对象必须具有 install,才能被 Vue.use() 方法安装
install
}
2、main.js中如下注册(即可全局使用)
import Tui from '../packages'
三、按需引入(局部注册)
// 在某个页面如下引入
import XXX from "路径"
export default {
components:{
XXX
}
}