Element UI按需加载之坑,this.$message和this.$notify不起作用了?

大家有遇到这种情况吗?elementUI组件使用报错,话不多说,直接上菜。

报错如下:

this.$message is not function

main.js引入了,组件不起作用,问题在于引入方式。

import {Message} from 'element-ui'
...
Vue.use(Message)

首先说一下调佣时的this是指向vue的原型就是vue.prototype,而这里的vue.use使用并没有把组件挂载在vue原型上,所以找不到这个function。

只要用vue.prototype挂载就可以了。

Vue.prototype.$message = Message;
this.$message({
   message: 'err',
   type: 'error',
});

不过vue原型挂载太多组件也是不太友好的,所以发现另一种方法。


如果不嫌麻烦也有另一种方法,就是那个页面用到就在那个页面引用和使用,简单粗暴。如下:

首先引入

import {Message} from 'element-ui'

这个组件也是一个方法,所以直接调佣

Message({
    message: '错误',
    type: 'warning',
});

这种方法比较麻烦,多个页面要用到就多个页面引入。


注意:以下组件的引用方式,尽量用Vue.prototype

Vue.prototype.$loading = Loading.service;
Vue.prototype.$msgbox = MessageBox;
Vue.prototype.$alert = MessageBox.alert;
Vue.prototype.$confirm = MessageBox.confirm;
Vue.prototype.$prompt = MessageBox.prompt;
Vue.prototype.$notify = Notification;
Vue.prototype.$message = Message;

所以使用组件时,要注意引用方式和使用方式。

描述如有错误,欢迎指正!

猜你喜欢

转载自blog.csdn.net/m0_70015558/article/details/125338627