vue.component和vue.use的用法

2019-11-13  本文已影响0人  清远_03d9

1. 注册全局组件

使用Vue.component()方法注册全局组件。
第一个参数是自定义元素名称,也就是将来在别的组件中使用这个组件的标签名称。
第二个参数是将要注册的Vue组件

import Vue from 'vue'; 
// 引入loading组件 
import Loading from './loading.vue'; 
// 将loading注册为全局组件,在别的组件中通过<loading>标签使用Loading组件 
Vue.component('loading', Loading);

2. 使用Vue.use注册插件

Vue.use(plugin)

1> 如果plugin(Vue.use的第一个参数)传入一个对象,对象中包含install方法,则调用这个plugin的install方法并将整理好的数组当成参数传入install方法中。 =>plugin.install.apply(plugin, args)

2. 如果传入的plugin就是一个函数,那么我们就直接调用这个函数并将整理好的数组当成参数传入。 =>plugin.apply(null, args)

实例1

import Vue from 'vue'; 
// 这个插件必须具有install方法 
const plugin = {
 install (Vue, options) { 
    // 添加全局方法或者属性 
    Vue.myGlobMethod = function () {}; 
    // 添加全局指令 
    Vue.directive(); 
    // 添加混入 
    Vue.mixin(); 
    // 添加实例方法 
    Vue.prototype.$xxx = function () {}; 
    // 注册全局组件 
    Vue.component() 
 } 
} 

    // Vue.use内部会调用plugin的install方法
    Vue.use(plugin);

实例2

//组件文件下的index文件
import Add from "./Add.vue"
export default (Vue)=>{
  Vue.component(Add.name,Add)
}

//src下的index文件中:
import Add from "./components/Add";
Vue.use(Add)
上一篇 下一篇

猜你喜欢

热点阅读