vuex从入门到出门

一般在大型的项目中,通常会用到vuex来管理,那么vuex到底是什么呢?

一、什么是vuex

  • 官方文档解释:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
  • 简单来说,一般在大型的项目中,如果有多个组件之间传值,频繁的调用使用组件传值会使数据变得不好管理。为此vue提供了一个可以统一管理的工具—vuex,可以把这些组件所使用的值存放在一个集中的地方,方便统一管理与调用。

二、vuex的使用

官网给出的vuex的使用示例图

在这里插入图片描述

state

----Vuex 使用单一状态树,就是保存所有数据的状态,相当于vue实例中的data

const store = new Vuex.Store({
  state: {
    datalist: []
  }
})

可以使用辅助函数**mapState**获取vuex中state里的数据状态

// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'

export default {
  // ...
  computed:{
  //这种写法不仅可以使用辅助函数,还可以定义写一些其他的方法
  ...mapState(['datalist'])
  },
  
  //官网写法
  //computed:mapState({
  //		//定义别名
  //      mydatalist:state=>state.datalist
  //  })
}

mutations

----改变state中数据状态的唯一方法是提交 mutation,也就是通过mutations里的函数更改,调用mutations里的函数使用store.commit(‘函数名’)

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // 变更状态
      state.count++
    }
  }
})

使用store.commit()方法调用调用此函数

store.commit('increment')

可以使用辅助函数**mapMutations**将组件中的 methods 映射为 store.commit 调用

// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapMutations } from 'vuex'

export default {
  methods:{
  //获取mutations中的方法
  ...mapMutations(['DEL'])
  //调用该方法
  this.DEL(id)//也可以直接在组件中使用 DEL(id)直接绑定click事件
  },
}

actions

------如果调用后端接口进行异步操作时,就需要通过actions来改变mutations里的方法,Action 类似于 mutation,不同在于:Action 提交的是 mutation,而不是直接变更状态。Action 可以包含任意异步操作。

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})

调用acitions使用store.dispatch()方法来触发

store.dispatch('increment')

可以使用辅助函数**mapActions**将组件的 methods 映射为 store.dispatch 调用

import { mapActions } from 'vuex'

export default {
  // ...
  methods: {
  // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
    ...mapActions([ 'increment'])
}

gettters

----Getter相当于vue中的computed计算属性

 getters:{
    pages(state){
      return Math.ceil(state.datalist.length/3)
    }
  },

可以使用辅助函数 **mapGetters**获取到vuex中的计算属性的值

import {mapGetters} from 'vuex'
export default {
    computed:{
        ...mapGetters(['pages'])
    },
}

modules

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

const moduleA = {
		namespaced:true,
	    state:{
	        num:100
	    },
	    mutations:{
	        ADDNUM(state){
	            state.num++
	        }
	    }
	  actions: { ... },
	  getters: { ... }
}

const moduleB = {
  state: {
  	name:'dny'
  },
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    moduleA,
    moduleB
  }
})

在组件中使用vuex,使用$store.state+模块名访问vuex模块的状态属性,如果需要调用模块中mutations中的方法,最好使用命名空间来区分每个模块里的方法

<template>
    <div>
        num:{{$store.state.moduleA .num}}
        name:{{$store.state.moduleB .name}}
        
        <!-- 命名空间 方法前面加引入模块的key的名字 -->
        <button @click='$store.commit("Cart/ADDNUM")'>点击</button>
    </div>
</template>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue3是目前最新的Vue.js版本,相比Vue2有很多新特性和更好的性能。而VuexVue.js官方推荐的状态管理工具,用于处理复杂的应用程序中的共享状态。 下面是Vue3和Vuex的基本使用方法: 1. 在项目中安装Vue3和Vuex: ```bash npm install vue@next vuex@next --save ``` 2. 创建一个store.js文件用于配置Vuex: ```javascript import { createStore } from 'vuex' const store = createStore({ state: { count: 0 }, mutations: { increment(state) { state.count++ } }, actions: { increment(context) { context.commit('increment') } }, getters: { getCount(state) { return state.count } } }) export default store ``` 这里我们定义了一个state对象来存储应用程序的状态,一个mutation函数来改变状态,一个action函数来分发mutation,一个getter函数来获取状态。 3. 在main.js中引入store: ```javascript import { createApp } from 'vue' import App from './App.vue' import store from './store' createApp(App).use(store).mount('#app') ``` 4. 在组件中使用Vuex: ```html <template> <div> <p>Count: {{ count }}</p> <button @click="increment">Increment</button> </div> </template> <script> import { mapGetters, mapActions } from 'vuex' export default { computed: { ...mapGetters(['getCount']), count() { return this.getCount } }, methods: { ...mapActions(['increment']) } } </script> ``` 这里我们使用了Vuex提供的mapGettersmapActions函数来映射state中的count属性和increment函数到组件中。 以上就是Vue3和Vuex的基本使用方法,可以根据自己的需求进行扩展和修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

胡肖一

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

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

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

打赏作者

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

抵扣说明:

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

余额充值