温馨提示×

vue中如何定义全局方法

vue
养鱼的猫咪
2215
2021-05-11 10:01:19
栏目: 编程语言

在vue中定义全局方法的方法:1.利用全局混入mixin定义;2.通过prototype挂载定义;3.使用Plugin方法定义;4.直接在vue文件中定义;

vue中如何定义全局方法

具体方法如下:

1.利用全局混入mixin定义全局方法

Vue.mixin(mixin)

new Vue({

store,

router,

render: h => h(App),

}).$mount('#app')

2.通过prototype挂载定义全局方法

Object.keys(tools).forEach(key => {

Vue.prototype[key] = tools[key]

})

3.使用Plugin方法定义全局方法

const install = function (Vue, opts) {

Vue.prototype.$pluginDemo = function () {

console.log('')

}

}

export default {

install

}

4.直接在vue文件中定义全局方法

//定义全局方法

this.$root.$on('test',function(){

console.log("test")

})

//销毁全局方法

this.$root.$off("test')

//调用全局方法

this.$root.$emit("test")

0