vuex使用方式(注意:如果不能使用,请查看版本)

本文介绍了如何在 Vue 项目中使用 Vuex 进行状态管理。首先,通过 `import` 和 `Vue.use(Vuex)` 挂载 Vuex 到 Vue。接着,详细阐述了 Vuex 的四大核心概念:state(用于设置初始状态)、mutations(同步更新 state)、actions(异步操作,通过 commit 调用 mutations)和 modules(实现模块化)。在 main.js 中,引入并挂载 store 实例到 Vue 根实例。最后强调,actions 分发可以触发 mutations,实现异步操作。

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

// 导入Vuex
1import Vuex from "vuex";
2// 挂载到Vue对象上
Vue.use(Vuex)`
// 创建对象并调用store 方法
3、let store = new Vuex.Store({
4、在vuex中共有四个对象分别是:
	1state (初始化状态,设置初始值)
	2、mutations (修改state 中的值 【不可修改异步状态】)
		// 如果需要传递值需要使用: this.$store.commit({type:'方法名',value:值})。的方式
		mutations: {
		increment (state) {
		// 变更状态
		state.count++
		}
		}
	3、active (修改state中的状态,可修改异步的)
		// 可直接调用mutaions 中的方法。
		actions: {
		increment (context) {
		context.commit('increment')
		}
		}
	4、model (模块式,可分割)
	
		const moduleA = {
	  state: () => ({ ... }),
	  mutations: { ... },
	  actions: { ... },
	  getters: { ... }
	  const moduleB = {
	  state: () => ({ ... }),
	  mutations: { ... },
	  actions: { ... }
	}

	const store = createStore({
	  modules: {
	    a: moduleA,
	    b: moduleB
	  }
	})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
}
// 官网参考地址
https://vuex.vuejs.org/zh/guide/actions.html#%E5%88%86%E5%8F%91-action
#### 最后需要在main.js中进入,并挂载
import store from './store' // 导入放到Vue对象上

new Vue({
  render: h => h(App),
  store,
  router,
}).$mount('#app')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值