vue3.2中的vuex使用详解

yizhihongxing

下面是关于vue3.2中的vuex使用详解的完整攻略。

1. 什么是Vuex

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

2. 如何使用Vuex

2.1 安装Vuex

在vue项目中使用Vuex,需要先安装Vuex。使用npm安装:

npm install vuex --save

2.2 Vue中使用Vuex

在Vue项目中,需要先引入Vuex,并将其挂载到Vue中。

import {createStore} from 'vuex'
import Vue from 'vue'

Vue.use(Vuex)

const store = createStore({
  state: {...},
  mutations: {...},
  actions: {...},
  getters: {...}
})

export default store

其中,state表示存储的状态值,mutations表示提交对状态的更改,actions表示异步操作,getters表示从state中派生出一些状态。

2.3 在组件中使用Vuex

在组件中使用Vuex,需要使用Vue提供的mapStatemapMutationsmapActionsmapGetters四个辅助函数进行状态管理。

2.3.1 mapState使用示例

mapState函数可以直接将Vuex的state映射到组件的计算属性中。

import {mapState} from 'vuex'

export default {
  // ...
  computed: {
    ...mapState({
      count: state => state.count
    })
  }
}

2.3.2 mapMutations使用示例

mapMutations函数可以将Vuex的mutations映射到组件的methods中。

import {mapMutations} from 'vuex'

export default {
  // ...
  methods: {
    ...mapMutations([
      'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
      'decrement' // 将 `this.decrement()` 映射为 `this.$store.commit('decrement')`
    ])
  }
}

2.3.3 mapActions使用示例

mapActions函数可以将Vuex的actions映射到组件的methods中。

import {mapActions} from 'vuex'

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

2.3.4 mapGetters使用示例

mapGetters函数可以将Vuex的getters映射到组件的计算属性中。

import {mapGetters} from 'vuex'

export default {
  // ...
  computed: {
    ...mapGetters([
      'doneTodosCount'
    ])
  }
}

3. 示例说明

3.1 示例一

下面是一个简单的示例,说明如何在Vuex中管理计数器的状态。

安装Vuex

使用npm安装Vuex:

npm install vuex

在Vue项目中使用Vuex

在Vue项目中,需要先引入Vuex,并将其挂载到Vue中。

import {createStore} from 'vuex'
import Vue from 'vue'

Vue.use(Vuex)

const store = createStore({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++
    },
    decrement(state) {
      state.count--
    }
  },
  actions: {
    incrementAsync({commit}) {
      setTimeout(() => {
        commit('increment')
      }, 1000)
    },
    decrementAsync({commit}) {
      setTimeout(() => {
        commit('decrement')
      }, 1000)
    }
  },
  getters: {
    doneTodosCount: state => {
      return state.count
    }
  }
})

export default store

在组件中使用Vuex

在组件中使用Vuex,需要使用Vue提供的mapStatemapMutationsmapActionsmapGetters四个辅助函数进行状态管理。

<template>
  <div>
    <span>{{count}}</span>
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
  </div>
</template>

<script>
import {mapState, mapMutations, mapActions, mapGetters} from 'vuex'

export default {
  computed: {
    ...mapState({
      count: state => state.count
    }),
    ...mapGetters([
      'doneTodosCount'
    ])
  },
  methods: {
    ...mapMutations([
      'increment',
      'decrement'
    ]),
    ...mapActions([
      'incrementAsync',
      'decrementAsync'
    ])
  }
}
</script>

3.2 示例二

下面是另一个示例,说明如何在Vuex中管理购物车的状态。

安装Vuex

使用npm安装Vuex:

npm install vuex

在Vue项目中使用Vuex

在Vue项目中,需要先引入Vuex,并将其挂载到Vue中。

import {createStore} from 'vuex'
import Vue from 'vue'

Vue.use(Vuex)

const store = createStore({
  state: {
    cart: []
  },
  mutations: {
    addToCart(state, product) {
      const item = state.cart.find(i => i.id === product.id)
      if (item) {
        item.quantity++
      } else {
        state.cart.push({...product, quantity: 1})
      }
    }
  },
  actions: {},
  getters: {
    cartCount: state => {
      return state.cart.reduce((count, item) => count + item.quantity, 0)
    }
  }
})

export default store

在组件中使用Vuex

在组件中使用Vuex,需要使用Vue提供的mapStatemapMutationsmapActionsmapGetters四个辅助函数进行状态管理。

<template>
  <div>
    <h2>购物车</h2>
    <p>商品数量:{{cartCount}}</p>
    <ul>
      <li v-for="item in cart" :key="item.id">{{item.name}} * {{item.quantity}}</li>
    </ul>
    <button @click="addToCart({id: 1, name: '商品1', price: 100})">加入购物车</button>
  </div>
</template>

<script>
import {mapState, mapMutations, mapActions, mapGetters} from 'vuex'

export default {
  computed: {
    ...mapState({
      cart: state => state.cart
    }),
    ...mapGetters([
      'cartCount'
    ])
  },
  methods: {
    ...mapMutations([
      'addToCart'
    ]),
    ...mapActions([
    ])
  }
}
</script>

以上就是关于vue3.2中的vuex使用详解的完整攻略以及两个示例的详细说明。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:vue3.2中的vuex使用详解 - Python技术站

(0)
上一篇 2023年5月27日
下一篇 2023年5月27日

相关文章

  • vue中SPA单页面应用程序详解

    Vue中SPA单页面应用程序详解 什么是SPA单页面应用程序 SPA全称Single Page Application,意为单页面应用程序。它是一种特殊的网页应用程序,其特点是整个网站只有一个HTML页面,但在页面加载后,所有的页面操作都在该页面上进行,通过Ajax技术实现页面的局部刷新,最终实现不刷新页面的情况下,达到与传统多页面网站相同的用户体验。 Vu…

    Vue 2023年5月27日
    00
  • 在vue中给后台接口传的值为数组的格式代码

    在Vue中向后台接口传递值需要通过HTTP请求发送数据,一般的格式都是以JSON格式发送。如果要发送一个数组到后台,则需要将该数组转换为JSON格式,再通过HTTP请求发送数据。下面是用数组给后台传值的详细攻略,包含两个示例说明。 将数组转换成JSON 在Vue中需要将数组转换为JSON字符串格式,以便HTTP请求进行发送。使用JSON.stringify(…

    Vue 2023年5月28日
    00
  • vue原理Compile之optimize标记静态节点源码示例

    Vue的Compile阶段是将模板解析成AST并分析依赖收集,生成渲染函数的阶段。在这个阶段,Vue会对静态节点进行标记,优化渲染性能。其中,有一个关键的标记项就是 optimize。 optimize的主要作用是标记已知的静态根节点。如果一个静态节点不是根节点,那么其子节点将可能会发生变化,需要被重新渲染。但是,如果该节点被标记为静态节点,则可以避免对其进…

    Vue 2023年5月28日
    00
  • vue-cli2.9.3 详细教程

    Vue CLI2.9.3 详细教程 Vue CLI2.9.3 是一个由 Vue 官方提供的命令行工具,用于快速搭建基于 Vue.js 的项目和 SPA 应用,可根据用户的选择预设一套规范的项目目录结构、开发规范、自动化构建及相关依赖库等。本教程将详细介绍如何使用 Vue CLI2.9.3 进行项目搭建以及配置。 安装 Vue CLI 命令行工具 首先,需要使…

    Vue 2023年5月27日
    00
  • vue scss后缀文件background-image路径错误的解决

    当使用Vue结合SCSS编写样式时,如果在样式中设置了background-image属性,并且设置的路径存在问题,那么会导致图片无法正常加载。下面是解决该问题的完整攻略: 问题分析 样式中设置background-image属性使用的是相对路径,而在Vue项目中,其相对路径往往是相对于main.js文件或者Vue组件所在位置的路径。如果图片的相对路径出现问…

    Vue 2023年5月28日
    00
  • 在Vue中实现添加全局store

    下面给您详细讲解在Vue中实现添加全局store的完整攻略: 步骤一:在Vue中创建store实例 在Vue中,我们可以使用Vuex来实现全局store功能,因此首先需要在Vue项目中安装并引用Vuex库: npm install vuex –save 在Vue项目中引用Vuex库: import Vuex from ‘vuex’ Vue.use(Vuex…

    Vue 2023年5月27日
    00
  • vue跳转同一路由报错的问题及解决

    下面是关于“vue跳转同一路由报错的问题及解决”的完整攻略。 一、问题现象 在Vue开发中,经常会遇到多个块之间跳转的场景。当你在路由表中定义好相应的路由,并且跳转到相同路由时,可能会出现以下两种报错信息: 如果是使用router.push进行路由跳转,报错信息如下: Uncaught (in promise) NavigationDuplicated: A…

    Vue 2023年5月28日
    00
  • 面试必备的13道可以举一反三的Vue面试题

    针对“面试必备的13道可以举一反三的Vue面试题”的完整攻略,我将从以下几个方面进行详细讲解: 题目概述 重点知识点 技巧提示 题目概述 这13道可以举一反三的Vue面试题涵盖了Vue中的基础知识点、常用功能及其用法、组件开发、状态管理等多个方面,对于Vue开发工程师的面试来说是非常有参考价值的。 重点知识点 以下是这13道面试题中的重点知识点: Vue实例…

    Vue 2023年5月27日
    00
合作推广
合作推广
分享本页
返回顶部