Vue2向Vue3过度Vuex核心概念module模块2

简介: Vue2向Vue3过度Vuex核心概念module模块2

7 综合案例 - 创建项目

  1. 脚手架新建项目 (注意:勾选vuex)
    版本说明:
    vue2 vue-router3 vuex3
    vue3 vue-router4 vuex4/pinia
vue create vue-cart-demo


  1. 将原本src内容清空,替换成教学资料的《vuex-cart-准备代码》

需求:

  1. 发请求动态渲染购物车,数据存vuex (存cart模块, 将来还会有user模块,article模块…)
  2. 数字框可以修改数据
  1. 动态计算总价和总数量

8 综合案例-构建vuex-cart模块

  1. 新建 store/modules/cart.js
export default {
  namespaced: true,
  state () {
    return {
      list: []
    }
  },
}
  1. 挂载到 vuex 仓库上 store/cart.js
import Vuex from 'vuex'
import Vue from 'vue'
import cart from './modules/cart'
Vue.use(Vuex)
const store = new Vuex.Store({
  modules: {
    cart
  }
})
export default store

9 综合案例-准备后端接口服务环境

  1. 安装全局工具 json-server (全局工具仅需要安装一次)
yarn global add json-server 或 npm i json-server  -g
  1. 代码根目录新建一个 db 目录
  2. 将资料 index.json 移入 db 目录
  3. 进入 db 目录,执行命令,启动后端接口服务 (使用–watch 参数 可以实时监听 json 文件的修改)
json-server  --watch  index.json

10 综合案例-请求动态渲染数据

1.目标

请求获取数据存入 vuex, 映射渲染

  1. 安装 axios
yarn add axios
  1. 准备actions 和 mutations
import axios from 'axios'
export default {
  namespaced: true,
  state () {
    return {
      list: []
    }
  },
  mutations: {
    updateList (state, payload) {
      state.list = payload
    }
  },
  actions: {
    async getList (ctx) {
      const res = await axios.get('http://localhost:3000/cart')
      ctx.commit('updateList', res.data)
    }
  }
}
  1. App.vue页面中调用 action, 获取数据
import { mapState } from 'vuex'
export default {
  name: 'App',
  components: {
    CartHeader,
    CartFooter,
    CartItem
  },
  created () {
    this.$store.dispatch('cart/getList')
  },
  computed: {
    ...mapState('cart', ['list'])
  }
}
  1. 动态渲染
<!-- 商品 Item 项组件 -->
<cart-item v-for="item in list" :key="item.id" :item="item"></cart-item>

cart-item.vue

<template>
  <div class="goods-container">
    <!-- 左侧图片区域 -->
    <div class="left">
      <img :src="item.thumb" class="avatar" alt="">
    </div>
    <!-- 右侧商品区域 -->
    <div class="right">
      <!-- 标题 -->
      <div class="title">{{item.name}}</div>
      <div class="info">
        <!-- 单价 -->
        <span class="price">¥{{item.price}}</span>
        <div class="btns">
          <!-- 按钮区域 -->
          <button class="btn btn-light">-</button>
          <span class="count">{{item.count}}</span>
          <button class="btn btn-light">+</button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: 'CartItem',
  props: {
    item: Object
  },
  methods: {
  }
}
</script>

11 综合案例-修改数量

  1. 注册点击事件
<!-- 按钮区域 -->
<button class="btn btn-light" @click="onBtnClick(-1)">-</button>
<span class="count">{{item.count}}</span>
<button class="btn btn-light" @click="onBtnClick(1)">+</button>
  1. 页面中dispatch action
onBtnClick (step) {
  const newCount = this.item.count + step
  if (newCount < 1) return
  // 发送修改数量请求
  this.$store.dispatch('cart/updateCount', {
    id: this.item.id,
    count: newCount
  })
}
  1. 提供action函数
async updateCount (ctx, payload) {
  await axios.patch('http://localhost:3000/cart/' + payload.id, {
    count: payload.count
  })
  ctx.commit('updateCount', payload)
}
  1. 提供mutation处理函数
mutations: {
  ...,
  updateCount (state, payload) {
    const goods = state.list.find((item) => item.id === payload.id)
    goods.count = payload.count
  }
},

12 综合案例-底部总价展示

  1. 提供getters
getters: {
  total(state) {
    return state.list.reduce((p, c) => p + c.count, 0);
  },
  totalPrice (state) {
    return state.list.reduce((p, c) => p + c.count * c.price, 0);
  },
},
  1. 动态渲染
<template>
  <div class="footer-container">
    <!-- 中间的合计 -->
    <div>
      <span>共 {{total}} 件商品,合计:</span>
      <span class="price">¥{{totalPrice}}</span>
    </div>
    <!-- 右侧结算按钮 -->
    <button class="btn btn-success btn-settle">结算</button>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
  name: 'CartFooter',
  computed: {
    ...mapGetters('cart', ['total', 'totalPrice'])
  }
}
</script>


目录
相关文章
|
5天前
|
存储 API
vue3中如何动态自定义创建组件并挂载
vue3中如何动态自定义创建组件并挂载
167 90
|
12天前
|
JavaScript
Vue3中路由跳转的语法
Vue3中路由跳转的语法
113 58
|
11天前
|
JavaScript 索引
Vue 2和Vue 3的区别以及实现原理
Vue 2 的响应式系统通过Object.defineProperty来实现,它为对象的每个属性添加 getter 和 setter,以便追踪依赖并响应数据变化。
22 9
|
12天前
|
JavaScript 开发工具
vite如何打包vue3插件为JSSDK
【9月更文挑战第10天】以下是使用 Vite 打包 Vue 3 插件为 JS SDK 的步骤:首先通过 `npm init vite-plugin-sdk --template vue` 创建 Vue 3 项目并进入项目目录 `cd vite-plugin-sdk`。接着,在 `src` 目录下创建插件文件(如 `myPlugin.js`),并在 `main.js` 中引入和使用该插件。然后,修改 `vite.config.js` 文件以配置打包选项。最后,运行 `npm run build` 进行打包,生成的 `my-plugin-sdk.js` 即为 JS SDK,可在其他项目中引入使用。
|
10天前
|
JavaScript 调度
Vue3 使用 Event Bus
Vue3 使用 Event Bus
18 1
|
11天前
|
JavaScript
Vue3 : ref 与 reactive
Vue3 : ref 与 reactive
11 1
vue3 reactive数据更新,视图不更新问题
vue3 reactive数据更新,视图不更新问题
|
11天前
|
JavaScript
|
11天前
vue3定义暴露一些常量
vue3定义暴露一些常量
|
10天前
Vue3 使用mapState
Vue3 使用mapState
11 0