Store就是全局变量都是可以双向绑定的,以下是模块的用法:
state定义的是变量名称,mutations里面是给变量赋值的方法
export default { namespaced: true, state: { //打开的Tabs tabs: null, //当前显示的key selectTabKey: null }, mutations: { setSelectTabKey(state, key) { state.selectTabKey = key; localStorage.setItem(process.env.ADMIN_TABS_SELECT_KEY, JSON.stringify(key)); }, setTabs(state, tabs) { state.tabs = tabs; localStorage.setItem(process.env.ADMIN_TABS_KEY, JSON.stringify(tabs)); }, initTabs(state, tab) { var localTabs = localStorage.getItem(process.env.ADMIN_TABS_KEY) if (localTabs != null) { state.tabs = JSON.parse(localTabs); state.selectTabKey = JSON.parse(localStorage.getItem(process.env.ADMIN_TABS_SELECT_KEY)); } else { state.selectTabKey = tab.key; localStorage.setItem(process.env.ADMIN_TABS_SELECT_KEY, JSON.stringify(state.selectTabKey)); state.tabs = []; state.tabs.push({ title: tab.title, icon: tab.icon, content: "", key: tab.key, closable: false, icon_bk: "", url: tab.url, }); localStorage.setItem(process.env.ADMIN_TABS_KEY, JSON.stringify(state.tabs)); } }, addTabs(state, tab) { state.selectTabKey = tab.key; localStorage.setItem(process.env.ADMIN_TABS_SELECT_KEY, JSON.stringify(state.selectTabKey)); var localTabs = localStorage.getItem(process.env.ADMIN_TABS_KEY) if (localTabs != null) { state.tabs = JSON.parse(localTabs); } if (state.tabs == null) { state.tabs = []; } //判断有没有在tabs里面 var isAdd = false; for (var pn of state.tabs) { if (pn.key == tab.key) { isAdd = true; break; } } if (isAdd == false) { state.tabs.push({ title: tab.title, icon: tab.icon, content: "", key: tab.key, closable: true, icon_bk: "", url: tab.url, }); } localStorage.setItem(process.env.ADMIN_TABS_KEY, JSON.stringify(state.tabs)); }, } }
然后整合模块
import menu from './menu' import tab from './tab' import setting from './setting' export default {menu, tab,setting}
对外输出
import Vue from 'vue' import 'es6-promise/auto' import Vuex from 'vuex' import modules from './modules' Vue.use(Vuex) const store = new Vuex.Store({modules}) export default store
Main方法注册
获取
this.$store.state.tab.selectTabKey
赋值
this.$store.commit("tab/setSelectTabKey", targetKey);
监控值改变
watch: { "$store.state.tab.selectTabKey": { handler: function (newVal, oldVal) { if (this.currTarger != newVal) { this.onTabChange(newVal); } }, }, },
可以直接绑定
注意点,全局变量存localstore的时候必须转JSONString,取的时候也得转,否则 绑定到控件上会失效
存
localStorage.setItem(process.env.ADMIN_TABS_SELECT_KEY, JSON.stringify(key));
取
state.selectTabKey = JSON.parse(localStorage.getItem(process.env.ADMIN_TABS_SELECT_KEY));
之前直接这样写会导致无法绑定到控件
localStorage.setItem(process.env.ADMIN_TABS_SELECT_KEY, key);
state.selectTabKey = localStorage.getItem(process.env.ADMIN_TABS_SELECT_KEY);
到此这篇关于Vue 关于Store的用法的文章就介绍到这了,更多相关Vue Store 用法内容请搜索插件窝以前的文章或继续浏览下面的相关文章希望大家以后多多支持插件窝!