Vuex的安装、搭建及案例详解

yizhihongxing

Vuex的安装

在使用Vuex之前,需要在项目中安装Vuex依赖包。可以通过npm或者yarn进行安装。

使用npm安装:

npm install vuex --save

使用yarn安装:

yarn add vuex

Vuex的搭建

Vuex的核心概念包括state、mutations、actions、getters和modules。

以下是一个简单的Vuex示例:

// store.js
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: {
    increment(context) {
      context.commit('increment');
    }
  },
  getters: {
    getCount: state => {
      return state.count;
    }
  },
  modules: {}
});

export default store;
  1. 首先,在项目中引入Vue和Vuex。
  2. 然后,创建一个新的Vuex store实例。
  3. 在store实例中,定义state对象,用于存储状态。
  4. 定义mutations对象,用于修改state中的数据。
  5. 定义actions对象,用于异步修改state中的数据。在actions中,可以调用mutations中的方法。
  6. 定义getters用于获取state中的数据。getters可以理解为state的计算属性。
  7. 最后,创建一个空的modules对象。

案例详解

简单的计数器

下面我们来看一个简单的计数器的案例。假设我们有一个计数器,可以实现加1、减1和重置的功能。

首先,在Vuex的store中定义state对象,用于存储计数器的值:

state: {
  count: 0
}

然后,定义mutations对象,用于修改count的值:

mutations: {
  increment(state) {
    state.count++;
  },
  decrement(state) {
    state.count--;
  },
  reset(state) {
    state.count = 0;
  }
}

接着,定义actions对象,用于异步修改state中的数据:

actions: {
  increment(context) {
    context.commit('increment');
  },
  decrement(context) {
    context.commit('decrement');
  },
  reset(context) {
    context.commit('reset');
  }
}

最后,定义getters用于获取state中的数据:

getters: {
  getCount: state => {
    return state.count;
  }
}

在组件中使用Vuex时,需要引入Vuex的store实例。在Vue组件中,可以使用$store对象来访问Vuex store中的state、mutations、actions和getters等对象。

<template>
  <div>
    <h1>当前计数器的值为:{{count}}</h1>
    <button @click="increment">加1</button>
    <button @click="decrement">减1</button>
    <button @click="reset">重置</button>
  </div>
</template>

<script>
export default {
  computed: {
    count() {
      return this.$store.getters.getCount;
    }
  },
  methods: {
    increment() {
      this.$store.dispatch('increment');
    },
    decrement() {
      this.$store.dispatch('decrement');
    },
    reset() {
      this.$store.dispatch('reset');
    }
  }
}
</script>

上面的代码中,我们使用了computed来计算count值,使用methods来触发actions中的方法。在methods中,使用this.$store.dispatch来调用actions中的方法。

购物车

在Vue.js中,用Vuex实现购物车的功能非常方便。下面我们来看一个购物车的示例。

首先,在Vuex的store中定义state对象,用于存储购物车的商品信息:

state: {
  cartList: []
}

然后,定义mutations对象,用于修改state中的购物车信息:

mutations: {
  addCartItem(state, item) {
    let index = state.cartList.findIndex(cartItem => {
      return cartItem.id === item.id;
    })
    if (index !== -1) {
      state.cartList[index].count++;
    } else {
      state.cartList.push(Object.assign(item, { count: 1 }));
    }
  },
  removeCartItem(state, item) {
    let index = state.cartList.findIndex(cartItem => {
      return cartItem.id === item.id;
    })
    state.cartList.splice(index, 1);
  },
  clearCart(state) {
    state.cartList = [];
  }
}

接着,定义actions对象,用于异步修改state中的购物车信息:

actions: {
  addCartItem(context, item) {
    context.commit('addCartItem', item);
  },
  removeCartItem(context, item) {
    context.commit('removeCartItem', item);
  },
  clearCart(context) {
    context.commit('clearCart');
  }
}

最后,定义getters用于获取state中的购物车信息:

getters: {
  getCartList: state => {
    return state.cartList;
  },
  getTotalPrice: state => {
    return state.cartList.reduce((total, item) => {
      return total + item.count * item.price;
    }, 0);
  },
  getTotalCount: state => {
    return state.cartList.reduce((total, item) => {
      return total + item.count;
    }, 0);
  }
}

在组件中使用Vuex来实现购物车的功能。

<template>
  <div>
    <ul>
      <li v-for="item in cartList" :key="item.id">
        <span>{{item.name}}</span>
        <span>{{item.price}}</span>
        <span>{{item.count}}</span>
        <button @click="addCartItem(item)">添加</button>
        <button @click="removeCartItem(item)">删除</button>
      </li>
    </ul>
    <div>
      <p v-if="cartList.length > 0">购物车总价:{{totalPrice}}</p>
      <p v-if="cartList.length > 0">购物车总数:{{totalCount}}</p>
      <button @click="clearCart">清空购物车</button>
    </div>
  </div>
</template>

<script>
export default {
  computed: {
    cartList() {
      return this.$store.getters.getCartList;
    },
    totalPrice() {
      return this.$store.getters.getTotalPrice;
    },
    totalCount() {
      return this.$store.getters.getTotalCount;
    }
  },
  methods: {
    addCartItem(item) {
      this.$store.dispatch('addCartItem', item);
    },
    removeCartItem(item) {
      this.$store.dispatch('removeCartItem', item);
    },
    clearCart() {
      this.$store.dispatch('clearCart');
    }
  }
}
</script>

上面的代码中,我们使用了computed来计算cartList、totalPrice和totalCount值,使用methods来触发actions中的方法。在methods中,使用this.$store.dispatch来调用actions中的方法。

以上就是Vuex的安装、搭建及案例详解的完整攻略。希望能对你的学习有所帮助。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Vuex的安装、搭建及案例详解 - Python技术站

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

相关文章

  • 简单聊聊vue3.0 sfc中setup的变化

    下面我就为大家详细讲解一下“简单聊聊vue3.0 sfc中setup的变化”。 一、什么是.vue文件 在介绍.vue文件的地方,就不得不介绍一下 Vue.js 了。Vue.js 是一款非常流行的前端框架,主要用于构建用户界面以及单页应用程序(SPA)。而.vue文件则是 Vue.js 在开发中所使用的组件文件格式,它可以包括 HTML、CSS 和 Java…

    Vue 2023年5月28日
    00
  • vue路由传参的基本实现方式小结【三种方式】

    下面是详细的“vue路由传参的基本实现方式小结【三种方式】”攻略: 一、query方式 在router-link中添加to属性,例如: <router-link :to="{path: ‘detail’, query: {id: 1, name: ‘foo’}}"> 去往详情 </router-link> 这里在t…

    Vue 2023年5月27日
    00
  • 使用Vue生成动态表单

    关于使用Vue生成动态表单的完整攻略,我们可以分为以下几个步骤: 步骤一:设计表单数据结构 首先,我们需要根据需求设计表单数据结构,包括表单元素类型、名称、value、placeholder、校验规则等信息。可以采用JSON格式来设计。 例如,我们要生成一个带有输入框、下拉框、单选框、多选框等元素的表单,可以按照如下格式来设计表单数据结构: formItem…

    Vue 2023年5月28日
    00
  • Vue使用vue-pdf实现PDF文件预览

    下面是“Vue使用vue-pdf实现PDF文件预览”的完整攻略。 什么是vue-pdf vue-pdf是一个基于pdf.js的Vue.js PDF查看器。支持多页和加密PDF文件。 实现方式 安装vue-pdf 在终端中运行以下命令安装 vue-pdf:npm install vue-pdf –save 引入vue-pdf 在Vue组件中引入vue-pdf…

    Vue 2023年5月28日
    00
  • 对Vue.js之事件的绑定(v-on: 或者 @ )详解

    当使用Vue.js开发web应用时,事件处理非常重要。Vue.js提供了一种非常方便的方式来处理事件,可以使用v-on指令(也可以简写为@)来绑定各种事件。 v-on指令(@) v-on可以绑定DOM元素的原生事件,例如click、keyup、submit等: <button v-on:click="handleClick">…

    Vue 2023年5月28日
    00
  • Vue.component的属性说明

    下面详细讲解一下Vue中的组件属性说明。 Vue.component的属性说明 在Vue中,组件的一些常用属性可以用Vue.component进行定义。下面是Vue.component的主要属性说明: props props属性用于接收父组件传递过来的数据,在组件内部通过 this.$props 访问。它是一个数组或对象,数组中的元素可以是字符串或对象。如果…

    Vue 2023年5月27日
    00
  • 用v-html解决Vue.js渲染中html标签不被解析的问题

    使用Vue.js时,如果在模板中绑定含有HTML标签的数据时,Vue.js会默认将其转义为纯文本,防止XSS攻击。有时候,开发者想要渲染出真正的HTML标签,就需要使用v-html指令。 以下是使用v-html指令解决Vue.js渲染中HTML标签不被解析的问题的攻略: 步骤一:在模板中使用v-html指令 在Vue.js的模板中使用v-html指令来解决H…

    Vue 2023年5月27日
    00
  • Vue 动态路由的实现详情

    下面就为大家详细讲解一下「Vue 动态路由的实现详情」。 什么是动态路由? Vue 路由是一种 URL 和组件之间的映射关系,并通过 URL 触发组件的展示。而动态路由则是在 URL 中传递参数,根据参数的不同动态匹配相应的路由。例如 /article/1 和 /article/2 都可以匹配到文章详情页路由,只不过参数不同。在 Vue 中,我们可以通过“路…

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