使用vuex实现组件间数据共享及修改status的值

tech2022-09-13  97

1、使用vuex,首先得安装它

npm install vuex --save

2、在store文件夹下的index.js引入vuex

import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { //存放组件间或全局中要用的值 isShowlog: false } }) export default store

3、在main.js中引入index.js

import store from './store' new Vue({ el: '#app', router, store, //这里一定要引入 render: h => h(App) })

4、这样就可以在每个组件中使用这个数据了

<Log v-if="$store.state.isShowlog"></Log>

5、当要修改这个值时,会调用actions事件,而调用此事件之前必须先调用dispatch事件,然后actions调用mutations,必须通过commit方法 在这里演示的是这种省略action,直接使用mutations,修改state中的值 在store文件夹下的index.js

import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { isShowlog: false }, mutations: { changeLog (state, isShowlog) { // 参数state指的是我们的所有公用数据 state.isShowlog= isShowlog } } }) handleLogClick (isShowlog) { this.$store.commit('changeLog', isShowlog) }

6、vuex获得state数据另一种写法

<template> <Log v-if="isShowlog"></Log> </template> <script> import {mapState} from 'vuex' export default { computed: { // 把state中的isShowlog属性映射到名字为isShowlog的计算属性之中 ...mapState(['isShowlog']) } } </script>

7、vuex修改state数据另一种写法 直接引入vuex的mapMutations API这样就不用使用调用this.$store.commit方法

import {mapState, mapMutations} from 'vuex' export default { methods: { routerTo (isShowlog) { this.changeLog(isShowlog) this.$router.push({path: '/'}) }, ...mapMutations(['changeLog']) } }

8、可以拆分store文件夹下的index.js 可以拆分成state.js、mutations.js,在index.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({ state, mutations })

9、但是当被改变页刷新时,isShowlog会变为原来的默认值,为了解决这个问题,要用到localStorage

mutations: { changeCity (state, isShowlog) { state.isShowlog= isShowlog try { if (localStorage.isShowlog) { localStorage.isShowlog= isShowlog } } catch (e) {} } }

在这里建议只要使用localStorage都在外面都包一层try…catch,防止用户在隐身模式或者关闭了本地存储功能下浏览器抛出异常

最新回复(0)