1. Mount the method to vue.Prototype
// Configure it in main.js of the project entry
import Vue from 'vue'
// Reset message to prevent repeated click repeat pop-up message box
import { message as Message } from "./resetMessage"
Vue.prototype.$message = Message
Copy the code
// After mounting, call this.$message
export default {
mounted() {
this.$message.success('Operation successful')}}Copy the code
2. Use global mixins
// mixin.js
export default {
data(){},methods: {
randomString(encode = 36, number = -8) {
return Math.random() // Generate a random number, 0.123456
.toString(encode) // Convert to base 36, "0.4fzyo82mvyr"
.slice(number) // truncate to "yo82mvyr"}}}Copy the code
// In the project entry main.js
import Vue from 'vue'
import mixin from '@/mixin'
Vue.mixin(mixin)
Copy the code
// Used in components
export default {
mounted() {
this.randomString()
}
}
Copy the code
3. Use Plugin
The vue. use implementation has no mount functionality, just triggers the install method of the plug-in, essentially using vue. prototype.
// plugin.js
import { message as Message } from "./resetMessage"
// install is the default method.
// When the component or function is used, the install method itself is called and a Vue class argument is passed.
const install = Vue {
Vue.prototype.$message = Message
...
}
export default {
install
}
Copy the code
// In the project entry main.js
import Vue from 'vue'
import plugin from '@/plugin'
Vue.use(plugin);
Copy the code
// Used in components
export default {
mounted() {
this.$message.success('Operation successful')}}Copy the code
4. Write global functions in vUE components
// Create a global method
this.$root.$on("fn".function () {
// ...
});
// Destroy the global method
this.$root.$off("fn");
// Call the global method
this.$root.$emit("fn");
Copy the code