Let's take a look, the description of the elementUI - Message document is as follows
global method
Element adds a global method $message to Vue.prototype . Therefore, in the vue instance, Message can be called in the way in this page.
Citation alone
Introduce Message separately:
import { Message } from 'element-ui';
At this point the method is called
Message(options)
. We also define individual methods for each type, egMessage.success(options)
. And can call toMessage.closeAll()
close all instances manually.
In short, if it is introduced globally, it can be used directly according to the documentation method, see below:
export default {
methods: {
open() {
this.$message.error('错误信息');
}
}
}
But if it is introduced separately, it can only be implemented in a vue single-file component like this:
import { Message } from 'element-ui';
export default {
methods: {
open() {
Message.error('错误信息');
}
}
}
In each component, Message needs to be introduced, which is too cumbersome. Can it be used like a global import this.$message
?
Problem cause and solution
Looking at element-ui/package/message/index.js
the implementation method below, it turns out that:
import Message from './src/main.js';
export default Message;
returned directly.
Other components generally have install
methods for Vue to operate.
Knowing the problem is easy to solve, just add the install method to Message.
// 和其他组件一样,一并引入
import {Button, Message} from 'element-ui'
// 在调用 Vue.use 前,给 Message 添加 install 方法
Message.install = function (Vue, options) {
Vue.prototype.$message = Message
}
// 和所有组件一样,一并进行use
Vue.use(Button)
Vue.use(Message)
Of course, it can also be implemented without Vue.use, such as writing directly on the Vue instance:
// 和其他组件一样,一并引入
import {Button, Message} from 'element-ui'
Vue.use(Button)
// 将 Message 直接挂在 Vue 实例上
Vue.prototype.$message = Message
I am more inclined to the first scheme, and the writing method is more regular.