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

本文介绍了如何使用Vuex进行组件间的数据共享,包括安装Vuex、在store文件夹和main.js中引入、直接操作mutations修改state值、使用mapMutations API简化代码、拆分store模块以优化维护,以及利用localStorage持久化状态,以解决页面刷新后数据丢失的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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,防止用户在隐身模式或者关闭了本地存储功能下浏览器抛出异常

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值