uniapp中vuex的基本使用

1. 创建一个uniapp项目

2. 在项目目录下用npm安装 vuex

npm install vuex --save

3. 在项目根目录下创建 store文件夹,在store文件夹中创建 index.js

 4. 在index.js中显式地通过 Vue.use() 来安装 Vuex:

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

Vue.use(Vuex)

5.在index.js中创建store

5.1 完整的store目录如下:

const store = new Vuex.Store({
  state: {
    // 存放状态
  },
  getters: {
    // state的计算属性
  },
  mutations: {
    // 更改state中状态的逻辑,同步操作
  },
  actions: {
    // 提交mutation,异步操作
  },
  // 如果将store分成一个个的模块的话,则需要用到modules。
   //然后在每一个module中写state, getters, mutations, actions等。
  modules: {
    a: moduleA,
    b: moduleB,
    // ...
  }
});

5.2 导出store

export default store

6. 在main.js 中引入store


vuex的基础用法

index.js

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

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		// 存放状态
		count:0,
		test:'这是store.js中的数据'
	},
	getters: {
		// state的计算属性
		//用 this.$store.getters.getData()读取
		getData(state){
			return state;
		}
	},
	mutations: {
		// 更改state中状态的逻辑,同步操作
		//用 this.$store.commit('function_name',payload) 使用,若无参数则不写payload
		add(state,n){
			state.count += n;
		}
	},
	actions: {
		// 提交mutation,异步操作
	}
})

export default store

原文地址:https://www.cnblogs.com/sunshine233/p/15339348.html