vue install 注册全局组件方式

 更新时间:2022年03月29日 09:16:44   作者:木槿之夏  
这篇文章主要介绍了vue install 注册全局组件方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

vue install注册全局组件

项目中的有些组件使用的频率比较高,这时候我们可以注册全局的组件,这样就不用每次使用的组件的时候一次次的导入

具体使用的步骤如下

一般会把这个常用的组件在main.js文件中注册好

1.首先先建立一个公用的组件

// Cmponent.vue 公用的组件
<template>
    <div>
        我是组件
    </div>
</template>
<script>
    export default { 
    }
</script>
<style scoped>
    div{
        font-size:40px;
        color:#fbb;
        text-align:center;
    }
</style>

2.新建一个install.js文件

import component from './Cmponent.vue'
const component = {
    install:function(Vue){
        Vue.component('component-name',component)
    }  //'component-name'这就是后面可以使用的组件的名字,install是默认的一个方法 component-name 是自定义的,我们可以按照具体的需求自己定义名字
}
// 导出该组件
export default component

3.在main.js文件中注册

// 引入组件
import install from '@plugins/install'; 
// 全局挂载utils
Vue.use(install);

4.在页面中使用

<template>
   <div>
      <component-name></component-name>
   </div>    
</template>

vue插件的install方法

MyPlugin.install = function (Vue, options) {
  // 1. 添加全局方法或属性
  Vue.myGlobalMethod = function () {
    // 逻辑...
  }
  // 2. 添加全局资源
  Vue.directive('my-directive', {
    bind (el, binding, vnode, oldVnode) {
      // 逻辑...
    }
    ...
  })
  // 3. 注入组件
  Vue.mixin({
    created: function () {
      // 逻辑...
    }
    ...
  })
  // 4. 添加实例方法
  Vue.prototype.$myMethod = function (methodOptions) {
    // 逻辑...
  }
}
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)

这里注意的就是vue插件的使用方法,通过全局方法 Vue.use() 使用插件。

插件通常会为 Vue 添加全局功能。插件的范围没有限制——一般有下面几种:添加全局方法或者属性;添加全局资源:指令/过滤器/过渡等;通过全局 mixin 方法添加一些组件选项;添加 Vue 实例方法,通过把它们添加到 Vue.prototype 上实现。

了解vue插件的install方法对我们写大型项目有很大帮助。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。 

相关文章

最新评论