在vuex中调用element的message的消息弹框:
我们首先在vuex中打印一下 this:
GETUSERINFO(state, userInfo) {
console.log(this)
console.log(this._vm.__proto__)
},
可以看到 _vm
就是vue 的实例对象,所以我们可以直接使用:
GETUSERINFO(state, userInfo) {
this._vm.$message.success(data.msg) // 成功提示
this._vm.$message.error(result.message) //失败提示
},
注意:这里必须使用第一种按需导入的方法把 ElementUI组件挂载到原型上。
按需引用 Element-UI
下载:
cnpm i element-ui -S
安装 babel-plugin-component 插件:
npm install babel-plugin-component -D
官网上让我们配置 .babelrc
文件,这里我们直接修改项目中的 babel.config.js
文件就好:
module.exports = {
presets: ["@vue/cli-plugin-babel/preset"],
plugins: [
[
"component",
{
libraryName: "element-ui",
styleLibraryName: "theme-chalk",
},
],
],
};
按需引入的第一种方式:
import Vue from 'vue';
import App from './App.vue';
import { Loading, MessageBox, Message } from 'element-ui';
/* 挂载到vue原型上 */
Vue.prototype.$loading = Loading.service;
Vue.prototype.$msgbox = MessageBox;
Vue.prototype.$message = Message;
new Vue({
el: '#app',
render: h => h(App)
});
按需引入的第二种方式:
在 main.js
中配置:
import Vue from 'vue';
import App from './App.vue';
import { Button, Select } from 'element-ui';
Vue.component(Button.name, Button); //这种方法和注册自定义全局组件类似
Vue.component(Select.name, Select);
/* 也可以直接用Vue.use
* Vue.use(Button)
* Vue.use(Select)
*/
new Vue({
el: '#app',
render: h => h(App)
});
把全局事件总线挂载到 vue原型上
一种组件间通信的方式,适用于
任意组件间通信
。
安装全局事件总线:
new Vue({
......
beforeCreate() {
Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm
},
......
})
使用事件总线:
接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的 回调留在A组件自身
。
data() {
return {
dome: []
}
},
mounted() {
//通过全局事件总线清除关键字
this.$bus.$on('xxxx',this.dome)
},
另一个通信组件提供数据:
this.$bus.$emit('xxxx',数据)
【实例】: 首页输入搜索词后点击跳转到搜索页面,此时应该通知搜索框组件
清空搜索的输入框。
data() {
return {
keyword: ''
}
},
mounted() {
//通过全局事件总线清除关键字
this.$bus.$on('clear', () => {
this.keyword = ''
})
},
this.$bus.$emit('clear') // Search页面 通知兄弟组件(搜索框组件)清除关键字
最好在
beforeDestroy
钩子中,用$off
去解绑当前组件所用到的事件。