vuex 按需动态引入等常用写法
作者:互联网
1、store目录下添加Chat.js
const Chat = { state: { path: "222222", token: "", subject: "" }, mutations: { SET_TOKEN: (state,data) => { state.token = data; } }, actions: { /** * this.$store.dispatch('setToken'); */ setToken({ commit, state }, data) { console.log(11111111111111) commit('SET_TOKEN',data); }, } } export default Chat
2、动态引入组件之前先加载store
// val 是否显示弹窗
showBtn(val){
if(!this.ChatMessage){ let options = { lock: true, text: '正在加载中...', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.8)', customClass: 'z-index-9999' } let loading = this.$loading(options) // 动态注入模块 this.$store.registerModule("chat", require("./store/chat").default);
// 动态引入组件
this.ChatMessage = () => import('@/views/admin/chatMsg'); let timesIndex = 0; timesIndex = setInterval(()=>{ if($(".ChatMessage").length) { clearInterval(timesIndex) loading.close(); } },200) } this.$store.state.chatMessageShowState = val; if(val) { $("body").addClass("overflow-h"); }else { $("body").removeClass("overflow-h"); }
}
3、页面中使用方法:
(1) 简单写法
console.log( this.$store.state.chat ) this.$store.dispatch('setToken');
(2)mapState的写法1
import { mapState } from "vuex"; computed: mapState({ path: (state) => state.chat.path, }), console.log(this.path)
(3)mapState的写法2
import { mapState } from "vuex";
computed: { ...mapState({ socket: (state) => state.chatSocket.socket, }), // 是否显示断网提示语 showTips() { return !this.networkStatus || this.websocketState!=1; // 断网 || 离线状态 }, },
标签:loading,val,vuex,mapState,state,引入,path,写法,store 来源: https://www.cnblogs.com/stella1024/p/16329674.html