vuex通透了

本文介绍了如何在Vue.js应用中使用Vuex进行状态管理,包括在index.js中设置全局store,模块化state、mutations、actions和getters,以及在组件中如何访问和操作这些状态。通过示例展示了Vuex如何简化状态管理,提高代码复用性和可维护性。
摘要由CSDN通过智能技术生成

目录结构

在这里插入图片描述

1.index.js

import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/cart.js'
import screen from './modules/products.js'
Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		username: '',
		age: 0,
		// 页面中通过this.$store.state.username
		/* 
		  在页面中,当一个组件需要获取多个状态的时候,
		  将这些状态都声明为计算属性会有些重复和冗余。 
		  为了解决这个问题,使用 mapState 辅助函数 帮助我们生成计算属性,让你少按几次键:
		  computed: 
		  ...mapState({
		             // 从state中拿到数据 箭头函数可使代码更简练
		             username: state => state.username,
					 'username',//映射 this.username 为 store.state.username
		             age: state => state.age,
					 // 页面的data中,firstName:"Li"
					 为了能够使用 this 获取组件自己的data数据,必须使用常规函数。
					 username: function (state) 
					 {
					        return this.firstName + ' ' +  state.username 
					 },
		         }) 
		 */
		todos: [{
				id: 1,
				done: true
			},
			{
				id: 2,
				done: false
			}
		]
	},
	// 相当于计算属性,getter 返回的值会根据它的依赖被缓存起来,
	// 且只有当它的依赖值发生改变才会被重新计算
	getters: {
		doneTodos: state => {
			return state.todos.filter(todo => todo.done)
		},
		doneTodosCount: (state, getters) => {
			//state :可以访问数据
			//getters:访问其他函数,等同于 store.getters
			return getters.doneTodos.length
		},
		getTodoById: (state) => (id) => {
			return state.todos.find(todo => todo.id === id)
		}
	},
	/* 页面中
	<view v-for="(item,index) in todos">
	            <view>{{item.id}}</view>
	            <view>{{item.text}}</view>
	            <view>{{item.done}}</view>
	</view>
	 computed: {
	             todos() {
	                 return this.store.getters.doneTodos
					 return this.$store.getters.getTodoById(2) 
	             }
	         }
	 */
	/* 
	 mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性:
	 // 使用对象展开运算符将 getter 混入 computed 对象中
	             ...mapGetters([
	                 'doneTodos',
	                 'doneTodosCount',
	                 // ...
	             ])
	 */
	modules: {
		cart,
		products
	},
})

export default store

cart.js (mutations)

import Vue from 'vue'
const state = {
	count: 1
}
/* 
当需要在对象上添加新属性时,你应该
使用 Vue.set(obj, 'newProp', 123), 或者
以新对象替换老对象。例如,利用对象展开运算符我们可以这样写:
state.obj = { ...state.obj, newProp: 123 } 
 */
const mutations = {
	/* add */
	/* state仓库,payload载荷(额外的参数) */
	add(state, payload) {
		// state.count += 1
		state.count += payload
	}
	/* 页面中
	  <view>
	         <view>数量:{{count}}</view>
	         <button @click="addCount">增加</button>
	  </view>
	  export default {
	      computed: {
	          count() {
	              return this.$store.state.count
	          }
	      },
	      methods: {
	          addCount() {
	              store.commit('add')
				  store.commit('add', 5)//每次累加 5
				  // 也可以传递一个对象
				  store.commit('add', { amount: 10 })
				  store.commit({
					  type: 'add',
					  amount: 6
				  })
	          }
			  ...mapMutations(['add'])//对象展开运算符直接拿到add
	      }
	  }
	 */
}

const actions = {

}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}

products.js(actions)

import {
	http
} from '../../utils/api.js'
const user = {
	state: {
		count: 1
	},

	mutations: {
		add(state) {
			// 变更状态
			state.count += 2
		}
	},

	actions: {
		// context对象和store具有相同的方法和属性
		addCountAction(context) {
			context.commit('add')
		}
		// 参数解构
		addCountAction({
			commmit
		}) {
			commit('add')
		}
		addCountAction(context) {
			//在执行累加的时候,会等待两秒才执行
			setTimeout(function() {
				context.commit('add')
			}, 2000)
		}
		/* addCountAction(context, payload) {
			context.commit('add', payload)
		}
		// 以载荷形式分发
		store.dispatch('addCountAction', {
			amount: 10
		}) */
		/* 
		 页面中
		  methods: {
		             add () {
		                 store.dispatch('addCountAction')
		             }
					 ...mapActions([ 'addCountAction', ])
					 // 将 `this.addCountAction()` 映射为 `this.$store.dispatch('addCountAction')`
					             
					  add () {
					             // 以对象形式分发
					             store.dispatch({
					                 type: 'addCountAction',
					                 amount: 5
					             })
					         }
		         }
		 */
		/* 
		  // 假设 getData() 和 getOtherData() 返回的是 Promise
		     actions: {
		         async actionA ({ commit }) {
		             commit('gotData', await getData())
		         },
		         async actionB ({ dispatch, commit }) {
		             await dispatch('actionA') // 等待 actionA 完成
		             commit('gotOtherData', await getOtherData())
		         }
		     }
		 */
		// 退出系统
		LogOut({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				uni.clearStorageSync();
				resolve()
			})
		},
		// 登入系统
		Login({
			commit,
			state,
			dispatch
		}, payload) {
			return new Promise((resolve, reject) => {
				uni.setStorageSync('token', payload.token);
				uni.setStorageSync('userInfo', payload.userInfo);
				dispatch('NotReadNum')
				resolve()
			})
		},
		// 重定向页面
		RedirectPage({
			commit,
			state,
			dispatch
		}) {
			return new Promise((resolve, reject) => {
				if (uni.getStorageSync('redirectPage')) {
					uni.reLaunch({
						url: uni.getStorageSync('redirectPage'),
						fail: () => {
							uni.showToast({
								title: '跳转失败,请联系管理员',
								duration: 2000,
								icon: "none"
							});
						},
						complete: () => {
							uni.removeStorageSync('redirectPage');
						}
					})
					resolve()
				} else {
					reject()
				}
			})
		}

	}
}

export default user

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值