Vue项目定义全局方法与全局组件


在介绍vue项目定义全局方法与组件之前,需要介绍下Vue.use的使用

Vue.use( plugin , options)

参数
plugin 插件 {Object | Function}
options 选项参数 数据类型任意

用法:安装 Vue.js 插件。如果插件是一个对象,必须提供 install 方法。如果插件是一个函数,它会被作为 install 方法。install 方法调用时,会将 Vue 作为参数传入。

/**
 * plugin作为不同参数示例
 **/
 
// Object
export default {
    
    
  install (Vue, options) {
    
    
    Vue.prototype.$console = () => {
    
    
      console.log('hello world')
    }
  }
}

// Function
export default (Vue, options) => {
    
    
  Vue.prototype.$console = () => {
    
    
    console.log('hello world')
  }
}

该方法需要在调用 new Vue() 之前被调用。

当 install 方法被同一个插件多次调用,插件将只会被安装一次。

参考插件

用 axios时,不需要用 Vue.use(axios),因为axios本身就不是Vue的组件,是个同时支持node端和浏览器端的http库。

vue项目定义全局方法

公共js文件,比如common.js通过export default暴露出来

export default {
    
    
  install(Vue, options){
    
    
  Vue.prototype.方法名 = function(){
    
    }
 }
}

在入口文件main.js引入

import commonJs form './utils/common'
Vue.use(commonJs)

然后就可以全局使用common.js里面的方法了,this.方法名

vue项目定义全局组件

1.创建如下图中的文件夹和文件
在这里插入图片描述
2.在 Loading.vue 中定义一个组件

<template>
    <div>
        Loading
    </div>
</template>

3.在 index.js 中 引入 Loading.vue ,并导出

// 引入组件
import LoadingComponent from './Loading.vue'
// 定义 Loading 对象
const Loading = {
    
    
    install (Vue, options){
    
    
        Vue.component('Loading',LoadingComponent)
    }
}
// 导出
export default Loading

4.在 main.js 中引入 Loading 文件下的 index

// 其中'@/components/Loading/index' 的 /index 可以不写,webpack会自动找到并加载 index 。如果是其他的名字就需要写上。
import Loading from '@/components/Loading'
// 这时需要 use(Loading),如果不写 Vue.use()的话,浏览器会报错,大家可以试一下
Vue.use(Loading)

5.在App.vue里面写入定义好的组件标签

<template>
  <div id="app">
    <h1>vue-loading</h1>
    <!-- 此处组件引用需要将驼峰法命名修改为'-'命名,且都是小写 -->
    <loading></loading>
  </div>
</template>

猜你喜欢

转载自blog.csdn.net/weixin_44116302/article/details/105294667
今日推荐