vue 插件机制

80 阅读1分钟

插件机制使用案例

// plugins/i18n.jsvar lan = {
    cn:{
       loginBtn:"登录"
    },
    en:{
        loginBtn:"Login"
    }
}
​
var KsdI18n =  {
    // install是插件定义入口方法,当你在使用vue.use(注册插件的时候)
    // 就会自动调用install方法,而参数app会自动注入进来,options必须在use的后面指定才会传入
    install: (app, options) => {
        // 在这里编写插件代码
       var lancontents  = lan[options.lan]
       console.log("lancontents",lancontents)
    }
}
​
​
​
// 导出
export default KsdI18n

main.js

import { createApp } from 'vue'
import '@/style.css'
import App from '@/App.vue'
import KsdI18n from '@/plugins/i18n'const app = createApp(App)
// 注册插件
app.use(KsdI18n,{lan:"cn"})
// 挂载
app.mount('#app')
​

用插件机制 全局注入组件

// index.js
import NowTime from './components/NowTime/index.js'const MyComponent = {
  install: (Vue) => {
    Vue.component('now-time', NowTime)
  }
}
export default MyComponent
// main.js
import MyComponent from './components/index.js'
Vue.use(MyComponent)

不使用插件机制 全局注入组件

// main.js
// 引入组件文件
import NowTime from './components/NowTime/now-time.vue'
// 直接使用Vue.component 对组件进行注册, 该组件名就是 Vue.component 的第一个参数
Vue.component('now-time', NowTime)

第一种方法它可以在注册组件的时候,给组件传入一些通用的属性。例如:字体大小、颜色等。具体靠 Vue.prototype实现

// index.js
import NowTime from './components/NowTime/index.js'const MyComponent = {
  install: (Vue,options) => {
    Vue.component('now-time', NowTime)
      Vue.prototype.$NOWTIME = {
      color: options.color || ''
    }
  }
}
export default MyComponent

在组件出直接使用 this.$NOWTIME.color

// now-time.vue
<template>
  <div :style="{ color: color}">
    当前时间为:{{ nowTime }}
  </div>
</template>
​
<script>
export default {
  data() {
    return {
      nowTime: new Date(),
      color: this.$NOWTIME.color
    }
  }
}
</script>
<style></style>

偷懒办法 把components下的组件全部进行全局注册

export default {
    install(app){
        // 全自动化过程注册全局组件,就不需要在引入在注册
        // 把src/components目录下的以.vue结尾的文件全部匹配出来。包括子孙目录下的.vue结尾的文件
         const modules = import.meta.glob('../components/**/*.vue');
         for(let key in modules){
             var componentName = key.substring(key.lastIndexOf('/')+1,key.lastIndexOf("."))
             app.component(componentName,modules[key])
         }
    }
}
import { App } from 'vue';

export default {
    install(app: App): void {
        const modules: Record<string, any> = import.meta.glob('../components/**/*.vue',{eager:true, import:'default'});

        for (const key in modules) {
            const componentName = key.substring(key.lastIndexOf('/') + 1, key.lastIndexOf('.'));
            app.component(componentName, modules[key]);
        }
    }
}

使用main.js

import Components from '@/components/index'
app.use(Components)