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导入