Vue定义全局变量和全局组件的几种方式

1.Vue.prototype

//template中使用console.log
Vue.prototype.$log = window.console.log;
Vue.prototype.$axios = axios    

window.$ = require("jquery")   //jquery挂载在window上

2.Vue.use()

import Element from "element-ui";
Vue.use(Element)

在这里插入图片描述
element暴露出来的东西,使用vue.use相当于install函数的调用

看一下vue.use的源码,发现其实就是函数的调用,1.如果为对象,就使用它的install方法(使用对象时必须要有install方法,否则白搭),2.如果为函数就直接调用

obj.install() || install()
import { toArray } from '../util/index'

export function initUse(Vue: GlobalAPI) {
  Vue.use = function (plugin: Function | Object) {
    const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
    if (installedPlugins.indexOf(plugin) > -1) {
      return this
    }

    // additional parameters
    const args = toArray(arguments, 1)
    args.unshift(this)
    //plugin为对象下面有install方法
    if (typeof plugin.install === 'function') {
      plugin.install.apply(plugin, args)
      // plugin为函数
    } else if (typeof plugin === 'function') {
      plugin.apply(null, args)
    }
    installedPlugins.push(plugin)
    return this
  }
}

3.Vue.directive()

自定义指令
在这里插入图片描述

//防止按钮重复点击,全局使用 v-preventClick
Vue.directive('preventClick', {
    inserted (el, binding) {
        el.addEventListener('click', () => {
           if (!el.disabled) {
               el.disabled = true
               setTimeout(() => {
                  el.disabled = false
               }, 3000)
            }
        })
    }
})

4.Vue.component()

const req = require.context('./components', true, /\.(vue)$/)
req.keys().forEach((item) => {
  const com = req(item).default
  // 全局注册
  if (com.name) {
    console.log(com);
    Vue.component(com.name, com)
  }
})
require.context(directory,useSubdirectories,regExp)

接收三个参数:
directory:文件路径
useSubdirectories:是否读取子文件
regExp: 正则匹配

5.Vue.extend()

vue 组件中有些需要将一些元素挂载到元素上,这个时候 extend 就起到作用了
用Vue.extend()构造出一个Vue子类实例,然后调用mount( ) 方法生成需要的DOM,再拿到对应的el实例,插入到DOM中

import Vue from 'vue'
const toastMessage = Vue.extend({
  template: '<div>{{ text }}</div>',
  data: function () {
    return {
      text: '发信息来啦'
    }
  }
})
const message = new toastMessage().$mount()
document.body.appendChild(message.$el)

6.Vue.filter()

差值表达式里的值从左向右传递,前面的值会以参数的形式传递给后面,它们之间以管道符分割

<div id="app">
    <p>{{price | addPriceIcon | editPrice}}</p>
</div>
 let vm = new Vue({
    el:"#app",
    data:{
        price:200
    },
    filters:{
        addPriceIcon(value){
            return '¥' + value
        },
        editPrice(value){
          console.log(value)
          return "吃饭:" + value
        }
    }
 })

如何区别使用?

相信很多人在用Vue使用别人的组件时,会用到 Vue.use() 。例如:Vue.use(VueRouter)、Vue.use(MintUI)。但是用 axios时,就不需要用 Vue.use(axios),就能直接使用。那这是为什么呐?
因为 axios 没有使用install方法

那么下面封装一个axios的install方法,这样就可以直接使用Vue.use(axios),使用get请求时直接用this.$get,使用post请求时直接用this.$post

export default {
  install(Vue) {
    Vue.prototype.$get = (url, params = {}) => {
      return new Promise((resolve, reject) => {
        axios.get(url, params)
          .then(response => resolve(response.data))
          .catch(error => reject(error))
      })
    }
    Vue.prototype.$post = (url, params = {}) => {
      return new Promise((resolve, reject) => {
        axios.post(url, params)
          .then(response => resolve(response.data))
          .catch(error => reject(error))
      })
    }
  }
}
  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值