Vuex状态管理模式详解

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

1.vuex的5种状态

{
	//state 存放数据,使用时通过 $store.state.counter 即可拿到数据,类似Vue中的data。
	state: {},
	//getters 处理state中的数据并返回新数据,具有缓存功能,类似计算属性computed
	getters: {},
	//mutations 突变,修改state的唯一方式,只能做同步操作,定义的方法名不能重复
	mutations: {},
	//actions 动作,处理异步操作,获取后台响应,提交数据给突变mutations
	actions: {},
	// 状态机可以有多个,modules用来存放各模块的状态机
	modules: {}
}

2.在vue-cli脚手架中使用

注意:vuex4版本以上只能在vue3中使用,vue2使用vuex3版本,安装时如果不指定版本,会安装最新版本的vuex

如果打印$store找不到,有可能版本不匹配  vue2使用vuex3 ,vue3 使用vuex4。

1.安装
npm install vuex@3 -S
2. store.js
import Vue from "vue";
import Vuex from 'vuex';

Vue.use(Vuex)

export default new Vuex.Store({
    state:{
        l_name:'测试四',
        l_count:4
    },
	getters:{
        fullNmae(state){
            return state.l_name+'111';
          }
    },
	mutations:{
        updateName(state,obj){
            console.log(obj);
            state.l_name = obj.lname;
        }
    },
	actions:{
        actionUpdateName(context,obj){
            console.log(obj);
            context.commit('updateName',obj)
        }
    },
	
})
3.注入仓库

Vuex 通过 store 选项,提供了一种机制将状态从根组件“注入”到每一个子组件中(需调用 Vue.use(Vuex)):main.js


import Vue from 'vue'
import App from './App'

//当前处于开发阶段,无需显示生产模式提示的信息。
Vue.config.productionTip = false;

import VueRouter from 'vue-router';
Vue.use(VueRouter);
import routes from './router/index';
import store from './store/store';

new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})
4.访问仓库数据

root根store取值

this.$store.state.counter

this.$store.getters.fullNmae

this.$store.commit('updateName',{'lname':'用户无'})

this.$store.dispatch('actionUpdateName',{'lname':'用户无'})

import { mapState, mapGetters, mapActions, mapMutations } from 'vuex';

...mapState(['l_name']),

...mapGetters(['fullNmae']),

<template>
  <div id="home">
        <p @click="upname">更换名字</p> 

        <p>{{l_name}}</p>
        <p>{{fullNmae}}</p>
  </div>
</template>

<script>

import  { mapState, mapGetters, mapActions, mapMutations } from 'vuex';


export default {
  
  data () {
    return {
      
    }
  },
 
  computed:{
  //   基础写法:
     l_name(){
         return this.$store.state.l_name
     },
  //  简化写法
    ...mapState(['l_name']),

//   基础写法:
     fullname(){
      return this.$store.getters.fullNmae
     },
 //  简化写法
     ...mapGetters(['fullNmae']),

  },

  
  methods:{

        ...mapMutations({
              upname(commit){
                commit('updateName',{'lname':'用户无'})
              }
          }),
          ...mapActions({
              upname(dispatch){
                dispatch('actionUpdateName',{'lname':'用户无'})
              }
          })

         
}
</script>

<style>

</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Vue.js是一个流行的JavaScript框架,它允许您构建动态Web应用程序。Vuex是一个专为Vue.js应用程序开发的状态管理模式。它允许您在应用程序中管理和维护状态,例如用户信息、购物车、主题等。Vuex状态存储在一个集中的存储库中,称为store。Vuex的核心概念包括state、mutations、actions和getters。 - state:存储应用程序级别的状态,可以通过store.state访问。 - mutations:用于更改状态的函数,必须是同步函数。可以通过store.commit方法调用。 - actions:用于处理异步操作的函数,可以包含任意异步操作。可以通过store.dispatch方法调用。 - getters:用于从store中获取状态的函数,可以通过store.getters访问。 下面是一个简单的示例,演示如何在Vue.js应用程序中使用Vuex: 1.安装Vuex ```shell npm install vuex --save ``` 2.创建store ```javascript import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }, getters: { getCount: state => { return state.count } } }) export default store ``` 3.在Vue组件中使用store ```javascript <template> <div> <p>Count: {{ count }}</p> <button @click="increment">Increment</button> <button @click="incrementAsync">Increment Async</button> </div> </template> <script> import { mapGetters, mapActions } from 'vuex' export default { computed: { ...mapGetters([ 'getCount' ]) }, methods: { ...mapActions([ 'increment', 'incrementAsync' ]) } } </script> ``` 在上面的示例中,我们创建了一个名为count的状态,并定义了一个名为increment的mutation和一个名为incrementAsync的action。我们还定义了一个名为getCount的getter,用于从store中获取count状态。在Vue组件中,我们使用mapGetters和mapActions帮助程序将getter和action映射到组件中。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cola-blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值