vue-cli项目中如何使用vuex(踩过的坑)

vuex知识学习梳理

一、在你的项目中安装Vuex 参考此文

二、在项目里新建好相关的文件,如图

项目文件结构

三、在index文件中配置如下

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(vuex)

import detailPicPage from "./detailPic/detailPicPage"

let store = new Vuex.Store({
  modules: {
    detailPicPage
  }
});
export default store

四、detailPicPage.js文件这样写

let detailPicPage = {
  state: {
    test1: "我是测试数据"
  },
  mutations:{
    setTest(state, data){
      state.test1 = data
    }
  }
}
export default detailPicPage

五、最后不要忘记在main.js文件中挂载vuex

import Vue from 'vue'
import App from './App'
import router from './router'
import Vuex from 'vuex'

Vue.config.productionTip = false

//注意下面的代码
Vue.use(Vuex);

//注意router选项,此处的写法等同于store: store
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

六、几个核心概念

1、state: 单一状态树,存放所有的状态数据。
2、mutation: 更改state的唯一方法就是提交mutation,mutation必须是同步函数。
3、namespaced: 是否使用命名空间。
4、getter: 可以异步的函数。

七、改变state的方式

import store from "@/store"
store.commit('detailPicPage/test1', '222')
// 注意,也可以不要import 直接this.$store.commit('detailPicPage/test1', '222')

八、组件中获取state的值

1、在组件中

import { mapState } from 'vuex'

2、在组件的computed属性里有俩中使用的方法

// 对象(需要更改键名时), 在组件中使用数据this.picInfor 和 this.PicInfor2
computed: {
  ...mapState("detailPicPage", {
    picInfor: state => state.test1,
    PicInfor2: state => state.test2
  })
}
// 数组(仓库数据键名同组件数据键名相同时),在组件中使用数据this.test1 和 this.test2
...mapState("detailPicPage", ["test1", "test2"])

九、组件中获取mutations中的方法

1、在组件中

import { mapMutations } from 'vuex'

2、在组件的methods属性里有俩中使用的方法

// 对象(需要更改方法名时), 在组件中使用数据this.picInfor() 和 this.PicInfor2()
methods: {
  ...mapState("detailPicPage", {
    picInfor: "setTest"
    PicInfor2: "setTest1"
  })
}
// 数组(仓库数据方法名同组件方法名相同时),在组件中使用数据this.setTest() 和 this.setTest1()
...mapState("detailPicPage", ["setTest", "setTest1"])

十、需要注意的几点

  • vuex中state的值是存储在运行内存中所以刷新页面会导致state中的值重置。参考文章
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值