Vuex入门教程(详细篇)

1.Vuex是什么

Vuex 是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享。
在这里插入图片描述
当我们的应用遇到多个组件共享状态(数据)时,就可以用到Vuex了。

2.Vuex的使用

安装完VueX后,在项目的src目录下新建store文件夹,然后在store目录下新建index.js(使用最新的Vue-CLI 4.x.x安装Vuex会自动配置好以下步骤)

store/index.js中 导入 Vuex 包并创建 Store 对象

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: { 
  },
  mutations: {
  },
  actions: {
  },
  getters:{
  }
})

main.js中将 store 对象挂载到 vue 实例中

import store from './store'

//.....

new Vue({
  render: h => h(App),
  // 将创建的共享数据对象,挂载到 Vue 实例中 
  // 所有的组件,就可以直接从 store 中获取全局的数据了 
  store,
}).$mount('#app')

3.Vuex的核心概念

Vuex 中的主要核心概念如下:

  • State
  • Mutation
  • Getter
  • Action

在上面的index.js中我们也可以看到一个Store对象就包含了这几个对象

3.1 State

State 提供唯一的公共数据源,所有共享的数据都要统一放到 Storestate 中进行存储。

3.1.1创建数据
  export default new Vuex.Store({ 
    state: { num: 0 } 
  })

然后我们在组件中访问 state 中数据的有两种方式:

3.1.2访问数据的第一种方式
this.$store.state.全局数据名称 //访问刚刚创建的num就是 this.$store.state.num
3.1.3访问数据的第二种方式
// 1. 从 vuex 中按需导入 mapState 函数 
import { mapState } from 'vuex' 

//.....

// 2. 将全局数据,映射为当前组件的计算属性 
computed: { 
  ...mapState(['num']) 
}
3.1.4组件代码与效果图
<template>
  <div id="app">
    <h1>num : {{this.$store.state.num}}</h1><!-- this.$store.state.全局数据名称 -->
    <h1>num : {{num}}</h1>
  </div>
</template>

<script>
import { mapState } from "vuex"; //从 vuex 中按需导入 mapState 函数 
export default {
  name: "App",
  //将全局数据,映射为当前组件的计算属性 
  computed: {
    ...mapState(["num"])
  }
};
</script>

在这里插入图片描述

3.2 Mutation

  1. mutations 用于变更 Store中 的数据。
  2. 只能通过 mutations变更 Store 数据,不可以直接操作 Store 中的数据。
  3. 通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化。
3.2.1定义Mutation
export default new Vuex.Store({
  state: { 
    num:0
  },
  mutations: {
    numAddOne(state){
      //num自增1
      state.num++;
    }
  }
})

和访问state数据一样,我们在触发mutations也有两种方式

3.2.2 触发Mutation的第一种方式
 methods:{
    addOne(){
       this.$store.commit('numAddOne')  //触发 mutations 的第一种方式 
    }
  }
3.2.3定义Mutation(带参数)
 mutations: {
    //n为参数
    numAddN(state,n){
      //num自增n
      state.num+=n;
    }
  },
3.2.3 触发Mutation的第二种方式
import {mapMutations } from "vuex";//从 vuex 中按需导入 mapMutations 函数

//...

methods:{
    ...mapMutations(['numAddN']),// 将指定的 mutations 函数,映射为当前组件的 methods 函数 
  }

3.2.4 组件代码与效果图
<template>
  <div id="app">
    <h1>num : {{this.$store.state.num}}</h1>  <!-- this.$store.state.全局数据名称 -->
    <button @click="addOne">+ 1</button>
    <h1>num : {{num}}</h1>
    <button @click="numAddN(3)">+ n</button>
  </div>  
</template>

<script>
import { mapState ,mapMutations } from "vuex";//从 vuex 中按需导入 mapMutations 函数
export default {
  name: "App",
  components: {},
  computed: {
    ...mapState(["num"])
  },
  data() {
    return {};
  },
  methods:{
    ...mapMutations(['numAddN']),// 将指定的 mutations 函数,映射为当前组件的 methods 函数 
    addOne(){
       this.$store.commit('numAddOne')  
    }
  }
};
</script>

在这里插入图片描述

3.3 Action

  1. Action 用于处理异步任务。
  2. 如果通过异步操作变更数据,必须通过 Action,而不能使用 Mutation,但是在 Action 中还是要通过触发 Mutation的方式间接变更数据。
3.3.1定义Action
export default new Vuex.Store({
  state: {
    num: 0
  },
   mutations: {
    numAddOne(state) {
      //num自增1
      state.num++;
    }
  },
  actions: {
    numAddOneAsync(context) {
       setTimeout(() => {
          context.commit('numAddOne') 
        }, 1000) 
      }
  }
})
3.3.2 触发Action的第一种方式
 methods:{
    addOneAsync(){
       this.$store.dispatch('numAddOneAsync')//触发 Action 
    }
  }
3.3.3 定义Action(带参数)
export default new Vuex.Store({
  state: {
    num: 0
  },
  mutations: {
    numAddN(state, n) {
      //num自增n
      state.num += n;
    }
  },
  actions: {
    //n为参数
    numAddNAsync(context,n) {
      setTimeout(() => {
        context.commit('numAddN',n)
      }, 1000)
    }
  }
})
3.3.4 触发Action的第二种方式
//从 vuex 中按需导入 mapActions 函数 
import { mapActions } from 'vuex' 

//.....

//将指定的 actions 函数,映射为当前组件的 methods 函数
methods: { 
  ...mapActions(['numAddNAsync']) 
}
3.3.4 组件代码与效果图
<template>
  <div id="app">
    <h1>num : {{this.$store.state.num}}</h1>  <!-- this.$store.state.全局数据名称 -->
    <button @click="addOne">+ 1</button>
    <br>
     <button @click="addOneAsync">+ 1 Async</button>
    <h1>num : {{num}}</h1>
    <button @click="numAddN(3)">+ n</button>
    <br>
    <button @click="numAddNAsync(3)">+ n Async</button>
  </div>  
</template>

<script>
import { mapState ,mapMutations ,mapActions } from "vuex";//从 vuex 中按需导入 mapXXXX 函数
export default {
  name: "App",
  components: {},
  computed: {
    ...mapState(["num"])
  },
  data() {
    return {};
  },
  methods:{
    ...mapActions(['numAddNAsync']) ,//将指定的 actions 函数,映射为当前组件的 methods 函数 
    ...mapMutations(['numAddN']),// 将指定的 mutations 函数,映射为当前组件的 methods 函数 
    addOne(){
       this.$store.commit('numAddOne')  //触发Mutation
    },
    addOneAsync(){
       this.$store.dispatch('numAddOneAsync')//触发 Action 
    }
  }
};
</script>

在这里插入图片描述

3.4 Getter

  1. Getter 用于对 Store 中的数据进行加工处理形成新的数据。
  2. Getter 可以对 Store 中已有的数据加工处理之后形成新的数据,类似 Vue 的计算属性 。
  3. Store 中数据发生变化,Getter 的数据也会跟着变化。
3.4.1 定义 Getter
export default new Vuex.Store({
  state: {
    num: 0
  },
  getters: {
  	//定义Getter 
    NumText(state ){
      return  '当前的num值为: '+ state.num 
    }
  }
})
3.4.2 使用Getter
使用 getters 的第一种方式
this.$store.getters.名称 //这里就是 this.$store.getters.NumText
使用 getters 的第二种方式
import { mapGetters } from 'vuex' 

 //.....
 
computed: { 
  ...mapGetters(['NumText']) 
}
3.3.4 组件代码与效果图
<template>
  <div id="app">
    <h1>{{this.$store.getters.NumText}}</h1>  <!-- this.$store.getters.名称 -->
    <button @click="addOne">+ 1</button>
    <br>
     <button @click="addOneAsync">+ 1 Async</button>
    <h1>{{NumText}}</h1>
    <button @click="numAddN(3)">+ n</button>
    <br>
    <button @click="numAddNAsync(3)">+ n Async</button>
  </div>  
</template>

<script>
import { mapState ,mapMutations ,mapActions,mapGetters  } from "vuex";//从 vuex 中按需导入 mapXXXX 函数
export default {
  name: "App",
  components: {},
  computed: {
    ...mapState(["num"]),
    ...mapGetters(['NumText']) 
  },
  data() {
    return {};
  },
  methods:{
     ...mapActions(['numAddNAsync']) ,//将指定的 actions 函数,映射为当前组件的 methods 函数 
    ...mapMutations(['numAddN']),// 将指定的 mutations 函数,映射为当前组件的 methods 函数 
    addOne(){
       this.$store.commit('numAddOne')  //触发Mutation
    },
    addOneAsync(){
       this.$store.dispatch('numAddOneAsync')//触发 Action 
    }
  }
};
</script>


在这里插入图片描述


目前正在学习前端,微信小程序…欢迎关注,一起学习!!!

  • 16
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
Vuex 是一个专门为 Vue.js 应用程序开发的状态管理库。它允许您在应用程序中集中管理状态,并且使得状态的变化可追踪、可调试和可维护。以下是一个简单的 Vuex 教程,帮助您开始使用 Vuex。 1. 安装 Vuex 您可以使用 npm 或 yarn 安装 Vuex,命令如下: ```bash npm install vuex ``` 或者 ```bash yarn add vuex ``` 2. 创建 Vuex Store 在您的 Vue.js 应用程序中,您需要先创建一个 Vuex Store。Store 是一个容器,它保存了应用程序中所有的状态(也称为 store)。在该容器中,您可以定义状态、修改状态以及监听状态的变化。 ```javascript import Vuex from 'vuex' import Vue from 'vue' Vue.use(Vuex) const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++ } }, actions: { increment(context) { context.commit('increment') } } }) export default store ``` 上面的代码中,我们定义了一个名为 `store` 的 Vuex Store。在 `state` 对象中,我们定义了一个名为 `count` 的状态。在 `mutations` 对象中,我们定义了一个名为 `increment` 的 mutation,该 mutation 用于修改 `count` 状态。在 `actions` 对象中,我们定义了一个名为 `increment` 的 action,该 action 用于调用 `increment` mutation。 3. 在 Vue.js 应用程序中使用 Vuex Store 您可以将 Vuex Store 注入到 Vue.js 应用程序中,以便在组件中使用。 ```javascript import Vue from 'vue' import App from './App.vue' import store from './store' new Vue({ el: '#app', store, render: h => h(App) }) ``` 在组件中,您可以使用 `mapState` 辅助函数来获取状态,并使用 `mapMutations` 辅助函数来提交 mutation。 ```javascript import { mapState, mapMutations } from 'vuex' export default { computed: { ...mapState(['count']) }, methods: { ...mapMutations(['increment']) } } ``` 4. 修改状态 在组件中,您可以使用 `this.$store.commit` 方法来提交 mutation,从而修改状态。 ```javascript methods: { increment() { this.$store.commit('increment') } } ``` 在 action 中,您可以使用 `context.commit` 方法来提交 mutation,从而修改状态。 ```javascript actions: { increment(context) { context.commit('increment') } } ``` 5. 使用 getter getter 可以对状态进行计算,从而派生出一个新的状态。在 Vuex Store 中,您可以使用 `getters` 对象定义 getter。 ```javascript const store = new Vuex.Store({ state: { count: 0, doubleCount: 0 }, mutations: { increment(state) { state.count++ } }, actions: { increment(context) { context.commit('increment') } }, getters: { doubleCount(state) { return state.count * 2 } } }) ``` 在组件中,您可以使用 `mapGetters` 辅助函数来获取 getter。 ```javascript import { mapGetters } from 'vuex' export default { computed: { ...mapGetters(['doubleCount']) } } ``` 这就是一个简单的 Vuex 教程。它可以帮助您开始使用 Vuex,但 Vuex 的功能远不止于此。如果您想深入了解 Vuex,请参阅 Vuex 官方文档。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值