Vue.prototype.和Vue.use

Vue.use  

 1、Vue.use的参数为对象

首先,创建一个plug1对象,在其内新增一个install属性,该属性为一个方法

let plug1 = {
	install(Vue) {
		Vue.prototype.$fn1 = function() {
			return '我是plug1'
		}
	}
}

export { plug1 }

 在main.js中引入

import Vue from 'vue'
import App from './App.vue'
import { plug1 } from './utils/index.js'

Vue.config.productionTip = false
Vue.use(plug1)

new Vue({
  render: h => h(App),
}).$mount('#app')

在任意一个页面中,就可以通过this.$fn1来全局调用

通过全局方法 Vue.use() 使用插件,要注意以下几点

1、Vue的插件是一个对象

2、插件对象必须有install字段

3、install字段是一个函数

4、初始化插件通过Vue.use

 2、Vue.use的参数为函数

新增plug2函数

// Vue.use的参数为对象
let plug1 = {
	install(Vue) {
		Vue.prototype.$fn1 = function() {
			return '我是plug1'
		}
	}
}

// Vue.use的参数为函数
function plug2(Vue) {
	Vue.prototype.$fn2 = function() {
		return '我是plug2'
	}
}

export { plug1, plug2 }

在main.js中引入

import Vue from 'vue'
import App from './App.vue'
import { plug1, plug2 } from './utils/index.js'

Vue.config.productionTip = false
Vue.use(plug1)
Vue.use(plug2)

new Vue({
  render: h => h(App),
}).$mount('#app')

 在任意一个页面中,同样也可以用this.$fn2来全局调用

上面的案例将 一个方法,一个对象通过 Vue.use 挂载到 Vue 的实例上面,在其他页面直接可以用 this 来调用 plug1 和 plug2 里面定义的方法。

注意: Vue.use 方法必须在 new Vue() 之前被调用。

Vue.prototype

每个页面都是一个vue的实例。Vue.prototype就是在实例上挂载属性/方法,在main.js中挂载属性/方法后,就可以在任意一个页面(实例)中,通过this.$xxx来使用这个属性/方法。

新建util.js文件

function formatDate(date, strM) {
  if (!date) return ''
  strM = strM || ''
  let year = date.getFullYear().toString()
  let month = (date.getMonth() + 1).toString() < 10 ? '0' + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString()
  let day = date.getDate().toString() < 10 ? '0' + date.getDate().toString() : date.getDate().toString()
  return year + strM + month + strM + day
}
export default {
  formatDate
}

在main.js中进行挂载操作

import Vue from 'vue'
import App from './App.vue'
import { plug1, plug2 } from './utils/index.js'
import utils from './utils/util.js'

Vue.config.productionTip = false
Vue.use(plug1)
Vue.use(plug2)
Vue.prototype.$utils = utils

new Vue({
  render: h => h(App),
}).$mount('#app')

在任意页面上调用此公共方法

  • 针对Vue编写的插件用Vue.use导入
  • 不是针对Vue编写的插件用Vue.prototype导入
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值