[vue] 怎么给vue定义全局的方法?
我知道的两种方式:
Object.keys(tools).forEach(key => {
Vue.prototype[key] = tools[key]
})
Vue.mixin(mixin)
new Vue({
store,
router,
render: h => h(App),
}).$mount('#app')
import tools from "./tools"
import filters from "./filters"
import Config from '../config'
import CONSTANT from './const_var'
export default {
data() {
return {
CONFIG: Config,
CONSTANT: CONSTANT
}
},
methods: {
// //将tools里面的方法挂载到vue上,以方便调用,直接this.$xxx方法名就可以了
// Object.keys(tools).forEach(key => {
// Vue.prototype[key] = tools[key]
// })
//将tools里面的方法用对象展开符混入到mixin上,以方便调用,直接this.$xxx方法名就可以了
...tools
},
filters: {
// //将filter里面的方法添加了vue的筛选器上
// Object.keys(filters).forEach(key => {
// Vue.filter(key, filters[key])
// })
...filters
}
}
我知道一种方法,就是在任意vue文件中写全局函数
// 创建全局方法
this.$root.$on('test', function(){
console.log('test');
})
// 销毁全局方法
this.$root.$off('test');
// 调用全局方法
this.$root.$emit('test');
prototype
1、通过prototype,这个非常方便。Vue.prototype[method]=method;
2、通过插件Vue.use(plugin);
3、通过mixin,Vue.mixin(mixins);
1.挂载到prototype上,上面说得vue.use的实现没有挂载的功能,只是触发了插件的install方法,本质还是使用了vue.prototype。
2.vue.mixin
方法一:给vue原型加方法:vue.protype.get=function(){}
1.挂载在prototype上,Vue.prototype
2.Vue.mixin
Vue.prototype Vue.mixin
Most helpful comment
我知道的两种方式: