vuex基本使用( state, getters, mutations, actions, modules )

1 篇文章 0 订阅

store/index.js 中创建 store

import { createStore } from 'vuex'
import other from './other'

export default createStore({
	// 这里的state就相当于组件中的data,就是专门用于保存共享数据的
	state: {
		count: 0,
		todos: [],
	},
	// 用于定义计算属性
	getters: {
		doneTodos: (state) => {
			return state.todos.filter(todo => todo.done)
	    },
	    // 接受其他 getter 作为第二个参数
	    doneTodosCount (state, getters) {
			return getters.doneTodos.length
		},
		// 通过让 getter 返回一个函数,来实现给 getter 传参
		getTodoById: (state) => (id) => {
			return state.todos.find(todo => todo.id === id)
		}
	},
	// 用于保存修改共享数据的方法
	// 注意点:在执行mutations中定义的方法的时候,系统会自动给这些方法传递一个state参数
	//         state中就保存了共享的数据
	//		   mutations必须是同步函数
	mutations: {
		increment (state, num) {
			state.count += num
		}
	},
	// 用于保存修改共享数据的方法
	// 注意点:接受一个与 store 实例具有相同方法和属性的 context 对象
	//         context中就包含state,commit,dispatch...
	//		   actions可以包含任意异步操作
	actions: {
		incrementAsync ({ state, commit }, payload) {
			setTimeout(() => {
				commit('increment', payload.num)
				}, 1000)
			}
		},
		// 解决action异步的方法
		actionA ({ state }) {
			return new Promise((resolve, reject) => {
				setTimeout(() => {
					console.log(state.count)
					resolve()
				}, 1000)
		}),
		actionB ({ dispatch, commit }) {
			return dispatch('actionA').then(() => {
				console.log()
			})
		}
	},
	modules: {
		other,
	}
})

子模块:store/other.js

import other from './other'

export default {
	state: {
		otherCount: 1
	},
	// 模块内部的 getter,根节点状态会作为第三个参数暴露出来
	getters: {
		sumWithRootCount (state, getters, rootState) {
			return state.otherCount + rootState.count
		}
	},
	mutations: {},
	// 模块内部的 action,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState
	actions: {
		fun1({state,rootState}){
			console.log( state.otherCount, rootState.count )
		}
	}
}

main.js 中注册 store

import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)
app.use(store)
app.mount('#app')

vue 组件中使用 store

import { mapState, mapGetters } from 'vuex'

export default {
	// ...
	computed: {
		...mapGetters([
			'doneTodosCount',
			// ...
		]),
		...mapState({
		   count: state => state.count,
		})
	},
	mounted:{
		console.log(this.$store.state.count)
		console.log(this.$store.getters.doneTodosCount)
		this.$store.commit('increment', 10)
		this.$store.dispatch('incrementAsync', {num: 10})
		this.$store.dispatch('actionA').then(() => {})
	},
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值