💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
1. 使用localStorage要使用try-catch进行包裹 ~~~ import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) function getCity(){ var defaultCity="新疆"; try { if(localStorage.getItem("city")){ defaultCity=localStorage.getItem("city") } } catch (error) { console.log(error) } return defaultCity; } export default new Vuex.Store({ //相当于data state: { letter:"", //取缓存 city:getCity() // city:"" }, mutations: { changeLetter(state,letter){ state.letter=letter }, changeCity(state,city){ // 设置缓存要使用trycatch包裹 try { localStorage.setItem("city",city) } catch (error) { console.log(error) } state.city=city } }, //接收子组件传递的事件1 将改变的值传给mutations actions: { changeLetter(ctx,letter){ // console.log(letter); // 通过commit传递 ctx.commit("changeLetter",letter) } } }) ~~~ 2. 封装vuex ~~~ 1. 新建store文件将store放入,修改min.js文件路径,将vuex中的模块拆分 //store.js import Vue from 'vue' import Vuex from 'vuex' import state from './state' import mutations from './mutations' Vue.use(Vuex) export default new Vuex.Store({ //相当于data state, mutations, //接收子组件传递的事件1 将改变的值传给mutations actions: { changeLetter(ctx,letter){ // console.log(letter); // 通过commit传递 ctx.commit("changeLetter",letter) } } }) //state.js function getCity(){ var defaultCity="新疆"; try { if(localStorage.getItem("city")){ defaultCity=localStorage.getItem("city") } } catch (error) { console.log(error) } return defaultCity; } export default{ letter:"", //取缓存 city:getCity() // city:"" } //mutations.js export default{ changeLetter(state,letter){ state.letter=letter }, changeCity(state,city){ // 设置缓存要使用trycatch包裹 try { localStorage.setItem("city",city) } catch (error) { console.log(error) } state.city=city } } ~~~