1. 将方法挂载到 Vue.prototype 上面
// 在项目入口的 main.js 里配置
import Vue from 'vue'
// 重置 message 防止重复点击重复弹出message弹框
import { message as Message } from "./resetMessage"
Vue.prototype.$message = Message
// 挂载之后,使用 this.$message 就可以调用
export default {
mounted() {
this.$message.success('操作成功')
}
}
2. 利用全局混入 mixin
// mixin.js
export default {
data() {
},
methods: {
randomString(encode = 36, number = -8) {
return Math.random() // 生成随机数字, 0.123456
.toString(encode) // 转化成36进制, "0.4fzyo82mvyr"
.slice(number) // 截取为 "yo82mvyr"
}
}
}
// 在项目入口 main.js 里配置
import Vue from 'vue'
import mixin from '@/mixin'
Vue.mixin(mixin)
// 在组件中使用
export default {
mounted() {
this.randomString()
}
}
3. 使用Plugin方式
Vue.use的实现没有挂载的功能,只是触发了插件的install方法,本质还是使用了Vue.prototype。
// plugin.js
import { message as Message } from "./resetMessage"
// install 是默认的方法。
// 当外界在 use 这个组件或函数的时候,就会调用本身的 install 方法,同时传一个 Vue 这个类的参数。
const install = Vue {
Vue.prototype.$message = Message
...
}
export default {
install
}
// 在项目入口 main.js 里配置
import Vue from 'vue'
import plugin from '@/plugin'
Vue.use(plugin);
// 在组件中使用
export default {
mounted() {
this.$message.success('操作成功')
}
}
4. vue 组件中写全局函数
// 创建全局方法
this.$root.$on("fn", function () {
// ...
});
// 销毁全局方法
this.$root.$off("fn");
// 调用全局方法
this.$root.$emit("fn");