Vue2基础十、Vuex

零、文章目录

Vue2基础十、Vuex

1、vuex概述

(1)vuex是什么
  • vuex 是一个 vue 的 状态管理工具,状态就是数据。
  • 大白话:vuex 是一个插件,可以帮我们管理 vue 通用的数据 (多组件共享的数据) 例如:购物车数据 个人信息数据
(2)场景
  • ① 某个状态 在 很多个组件 来使用 (个人信息)
  • ② 多个组件 共同维护 一份数据 (购物车)

image-20230724221016553

(3)优势
  • ① 共同维护一份数据,数据集中化管理
  • 响应式变化
  • ③ 操作简洁 (vuex提供了一些辅助函数)
(4)注意点
  • 不是所有的场景都适用于vuex,只有在必要的时候才使用vuex
  • 使用了vuex之后,会附加更多的框架中的概念进来,增加了项目的复杂度 (数据的操作更便捷,数据的流动更清晰)

2、构建 vuex环境

  • 目标:基于脚手架创建项目,构建 vuex 多组件数据共享环境

image-20230724221843685

  • 效果是三个组件, 共享一份数据:
    • 任意一个组件都可以修改数据
    • 三个组件的数据是同步的
(1)创建项目
vue create vuex-demo
(2)创建组件目录如下
|-components
|--Son1.vue
|--Son2.vue
|-App.vue
  • App.vue引入 Son1 和 Son2 子组件
<template>
  <div id="app">
    <h1>根组件</h1>
    <input type="text">
    <Son1></Son1>
    <hr>
    <Son2></Son2>
  </div>
</template>

<script>
import Son1 from './components/Son1.vue'
import Son2 from './components/Son2.vue'

export default {
  name: 'app',
  data: function () {
    return {

    }
  },
  components: {
    Son1,
    Son2
  }
}
</script>

<style>
#app {
  width: 600px;
  margin: 20px auto;
  border: 3px solid #ccc;
  border-radius: 3px;
  padding: 10px;
}
</style>
  • main.js
import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
    
    
  render: h => h(App)
}).$mount('#app')
  • components/Son1.vue
<template>
  <div class="box">
    <h2>Son1 子组件</h2>
    从vuex中获取的值: <label></label>
    <br>
    <button>值 + 1</button>
  </div>
</template>

<script>
export default {
      
      
  name: 'Son1Com'
}
</script>

<style lang="css" scoped>
.box{
      
      
  border: 3px solid #ccc;
  width: 400px;
  padding: 10px;
  margin: 20px;
}
h2 {
      
      
  margin-top: 10px;
}
</style>

  • components/Son2.vue
<template>
  <div class="box">
    <h2>Son2 子组件</h2>
    从vuex中获取的值:<label></label>
    <br />
    <button>值 - 1</button>
  </div>
</template>

<script>
export default {
      
      
  name: 'Son2Com'
}
</script>

<style lang="css" scoped>
.box {
      
      
  border: 3px solid #ccc;
  width: 400px;
  padding: 10px;
  margin: 20px;
}
h2 {
      
      
  margin-top: 10px;
}
</style>
(3)创建Vuex数据仓库

image-20230725211223321

  1. **安装 vuex:**安装vuex与vue-router类似,vuex是一个独立存在的插件,如果脚手架初始化没有选 vuex,就需要额外安装。
yarn add vuex@3 或者 npm i vuex@3
  1. **新建 store/index.js 专门存放 vuex:**为了维护项目目录的整洁,在src目录下新建一个store目录其下放置一个index.js文件。 (和 router/index.js 类似)

image-20230725211435982

  1. **Vue.use(Vuex)创建仓库 new Vuex.Store():**在store/index.js中,使用Vuex
// 导入 vue
import Vue from 'vue'
// 导入 vuex
import Vuex from 'vuex'
// vuex也是vue的插件, 需要use一下, 进行插件的安装初始化
Vue.use(Vuex)

// 创建仓库 store
const store = new Vuex.Store()

// 导出仓库
export default store
  1. 在 main.js 中导入挂载到 Vue 实例上
import Vue from 'vue'
import App from './App.vue'
import store from './store'

Vue.config.productionTip = false

new Vue({
    
    
  render: h => h(App),
  store
}).$mount('#app')
  • 至此,就成功创建了一个 空仓库!!
  1. 测试打印Vuex:在App.vue打印Vuex
created(){
  console.log(this.$store)
}

3、核心概念-state状态

  • 状态,即数据,明确如何给仓库 提供 数据,如何 使用 仓库的数据
(1)提供数据
  • State 提供唯一的公共数据源,所有共享的数据都要统一放到 Store 中的 State 中存储。
  • 打开项目中的store.js文件,在state对象中可以添加我们要共享的数据。
// 创建仓库 store
const store = new Vuex.Store({
    
    
  // state 状态, 即数据, 类似于vue组件中的data,
  // 区别:
  // 1.data 是组件自己的数据, 
  // 2.state 中的数据整个vue项目的组件都能访问到
  state: {
    
    
    count: 101
  }
})
(2)使用数据-通过store直接访问
获取 store:
 1.Vue模板中获取 this.$store
 2.js文件中获取 import 导入 store


模板中:     {
    
    {
    
     $store.state.xxx }}
组件逻辑中:  this.$store.state.xxx
JS模块中:   store.state.xxx
  • 模板中使用:组件中可以使用 $store 获取到vuex中的store对象实例,可通过state属性获取count, 如下
<h1>state的数据 - {
   
   { $store.state.count }}</h1>
<h1>state的数据 - {
   
   { count }}</h1>

// 把state中数据,定义在组件内的计算属性中
  computed: {
    count () {
      return this.$store.state.count
    }
  }
  • js文件中使用
//main.js

import store from "@/store"

console.log(store.state.count)
(3)使用数据-辅助函数mapState
  • 每次一个个的提供计算属性太麻烦了,我们可以通过mapState辅助函数把 store中的数据 自动 映射到 组件的计算属性中

image-20230726102146723

import {
    
     mapState } from 'vuex'

computed: {
    
    
    ...mapState(['count'])
}
  • 上面代码等价于
count () {
    
    
    return this.$store.state.count
}
  • 直接在代码中调用即可
 <div> state的数据:{
    
    {
    
     count }}</div>

4、核心概念-mutations

(1)单向数据流
  • vuex 同样遵循单向数据流,组件中不能直接修改仓库的数据

image-20230726103718639

  • Son1.vue:this.$store.state.count++ (错误写法),但是vue默认不会监测,监测需要成本
<button @click="handleAdd">值 + 1</button>


methods:{
	 handleAdd (n) {
      // 错误代码(vue默认不会监测,监测需要成本)
       this.$store.state.count++
      // console.log(this.$store.state.count) 
    },
}
(2)开启严格模式
  • 通过 strict: true 可以开启严格模式,开启严格模式后,直接修改state中的值会报错
  • state数据的修改只能通过mutations,并且mutations必须是同步

image-20230726104855825

(3)mutations操作流程
  1. 定义 mutations 对象,对象中存放修改 state 的方法
const store = new Vuex.Store({
    
    
	state: {
    
    
		count: 0
	},
	// 定义mutations
	mutations: {
    
    
		// 第一个参数是当前store的state属性
		addCount (state) {
    
    
		state.count += 1
		}
	}
})
  1. 组件中提交调用 mutations
this.$store.commit('addCount')
(4)mutations带参数
  • 看下面这个案例,每次点击不同的按钮,加的值都不同,每次都要定义不同的mutations处理吗?

image-20230726105843162

  • 提交 mutation 是可以传递参数的 this.$store.commit( 'xxx', 参数 )

  • 带参数的mutations操作流程如下:

    • 提供带参数的mutation函数
    mutations: {
          
          
      ...
      addCount (state, count) {
          
          
        state.count = count
      }
    },
    
    • 页面中提交调用 mutation
    handle ( ) {
          
          
      this.$store.commit('addCount', 10)
    }
    
    • 提交的参数只能是一个, 如果有多个参数要传, 可以传递一个对象
    this.$store.commit('addCount', {
          
          
      count: 10,
      ...
    })
    
(5)案例-减法功能

image-20230726110742233

  • Son2.vue
    <button @click="subCount(1)">值 - 1</button>
    <button @click="subCount(5)">值 - 5</button>
    <button @click="subCount(10)">值 - 10</button>

    export default {
        methods:{
             subCount (n) { 
                this.$store.commit('addCount', n)
        },
        }
    }
  • store/index.js
mutations:{
    
    
    subCount (state, n) {
    
    
      state.count -= n
    },
}
(6)案例-双向绑定

image-20230726110726139

image-20230726111833997

  • App.vue
<input :value="count" @input="handleInput" type="text">

export default {
  methods: {
    handleInput (e) {
      // 1. 实时获取输入框的值
      const num = +e.target.value
      // 2. 提交mutation,调用mutation函数
      this.$store.commit('changeCount', num)
    }
  }
}
  • store/index.js
mutations: {
    
     
   changeCount (state, newCount) {
    
    
      state.count = newCount
   }
},
(7)辅助函数mapMutations
  • mapMutations把mutations中的方法映射到methods
import  {
    
     mapMutations } from 'vuex'
methods: {
    
    
    ...mapMutations(['addCount'])
}
  • 上面代码等价于
methods: {
    
    
      // commit(方法名, 载荷参数)
      addCount () {
    
    
          this.$store.commit('addCount')
      }
 }
  • 通过this.addCount调用
<button @click="addCount">+1</button>
  • 注意: Vuex中mutations中要求不能写异步代码,如果有异步的ajax请求,应该放置在actions中

5、核心概念-actions

(1)actions概念
  • state:存放数据
  • mutations:同步更新数据 (便于监测数据的变化,记录调试)
  • actions:异步操作

image-20230726135047678

(2)actions操作流程

  • 提供action 方法
actions: {
    
    
  setAsyncCount (context, num) {
    
    
    // 一秒后, 给一个数, 去修改 num
    setTimeout(() => {
    
    
      context.commit('changeCount', num)
    }, 1000)
  }
},
  • 页面中 dispatch 调用
this.$store.dispatch('setAsyncCount', 200)
(3)辅助函数mapActions
  • mapActions 是把位于 actions中的方法映射到组件methods
import { mapActions } from 'vuex'
methods: {
   ...mapActions(['changeCountAction'])
}
  • 上面代码等价于
methods: {
    
    
  changeCountAction (n) {
    
    
    this.$store.dispatch('changeCountAction', n)
  },
}
  • 通过 this.方法就可以调用
<button @click="changeCountAction(200)">+异步</button>

6、核心概念-getters

(1)getters概念
  • 除了state之外,有时我们还需要从state中派生出一些状态,这些状态是依赖state的,此时会用到getters
(2)getters操作流程
  • 例如:state中定义了list,为 1-10 的数组,组件中,需要显示所有大于5的数据
state: {
    
    
    list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
  • 定义 getters
  getters: {
    
    
    // (1) getters函数的第一个参数是 state
    // (2) getters函数必须要有返回值
     filterList:  state =>  state.list.filter(item => item > 5)
  }
  • 通过 store 访问 getters
{
    
    {
    
     $store.getters.filterList }}
(3)辅助函数mapGetters
  • mapActions 是把位于 getters中的属性映射到组件computed
computed: {
    
    
    ...mapGetters(['filterList'])
}
  • 上面代码等价于
computed: {
    
    
    filterList(){
    
    
        return $store.getters.filterList;
    }    
}
  • 直接在代码中就可以使用
{
    
    {
    
     filterList }}

7、核心概念-module(进阶)

(1)module概念
  • 由于 vuex 使用单一状态树,应用的所有状态会集中到一个比较大的对象。
  • 当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
  • 由此,又有了Vuex的模块化。

image-20230726150041126

(2)模块拆分
  • 定义两个模块 usersetting

  • modules/user.js:user中管理用户的信息状态 userInfo

const state = {
  userInfo: {
    name: 'zs',
    age: 18
  }
}

const mutations = {}

const actions = {}

const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}

  • modules/setting.js:setting中管理项目应用的 主题色 theme,描述 desc
const state = {
  theme: 'dark'
  desc: '描述真呀真不错'
}

const mutations = {}

const actions = {}

const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
  • store/index.js文件中的modules配置项中,注册这两个模块
import user from './modules/user'
import setting from './modules/setting'

const store = new Vuex.Store({
    
    
    modules:{
    
    
        user,
        setting
    }
})
(3)使用模块state数据
  • 尽管已经分模块了,但其实子模块的状态,还是会挂到根级别的 state 中,属性名就是模块名

image-20230726150824586

  • 使用模块中的数据

    1. 通过模块名访问:$store.state.模块名.xxx

    2. 通过 mapState 映射:

      1. 默认根级别的映射:mapState([ 'xxx' ])

      2. 子模块的映射 :mapState('模块名', ['xxx']) - 需要开启命名空间 namespaced:true(对应模块文件中开启)

      export default {
              
              
        namespaced: true,
        state,
        mutations,
        actions,
        getters
      }
      
  • 代码演示

    • $store直接访问
    $store.state.user.userInfo.name
    
    • mapState辅助函数访问
    ...mapState('user', ['userInfo']),
    ...mapState('setting', ['theme', 'desc']),
    
(4)使用模块getters数据
  • 使用模块getters数据

    1. 通过模块名访问:$store.getters['模块名/xxx ']

    2. 通过 mapGetters 映射

      1. 默认根级别的映射:mapGetters([ 'xxx' ])
      2. 子模块的映射:mapGetters('模块名', ['xxx']) - 需要开启命名空间
  • 代码实现

    • 定义模块modules/user.js
    const getters = {
          
          
      // 分模块后,state指代子模块的state
      UpperCaseName (state) {
          
          
        return state.userInfo.name.toUpperCase()
      }
    }
    
    • Son1.vue 通过模块名访问
    <div>{
          
          {
          
           $store.getters['user/UpperCaseName'] }}</div>
    
    • Son2.vue 通过 mapGetters 映射
    computed:{
          
          
      ...mapGetters('user', ['UpperCaseName'])
    }
    
(5)使用模块mutations方法
  • 注意:默认模块中的 mutation 和 actions 会被挂载到全局,需要开启命名空间,才会挂载到子模块。

  • 使用模块mutations方法

    1. 通过 store 调用:$store.commit('模块名/xxx ', 额外参数)

    2. 通过 mapMutations 映射

      1. 默认根级别的映射:mapMutations([ 'xxx' ])
      2. 子模块的映射:mapMutations('模块名', ['xxx']) - 需要开启命名空间
  • 代码实现

    • 定义模块modules/user.js
    const mutations = {
          
          
      setUser (state, newUserInfo) {
          
          
        state.userInfo = newUserInfo
      }
    }
    
    • 定义模块modules/setting.js
    const mutations = {
          
          
      setTheme (state, newTheme) {
          
          
        state.theme = newTheme
      }
    }
    
    • Son1.vue通过 store 调用
    <button @click="updateUser">更新个人信息</button> 
    <button @click="updateTheme">更新主题色</button>
    
    export default {
      methods: {
        updateUser () {
          // $store.commit('模块名/mutation名', 额外传参)
          this.$store.commit('user/setUser', {
            name: 'xiaowang',
            age: 25
          })
        }, 
        updateTheme () {
          this.$store.commit('setting/setTheme', 'pink')
        }
      }
    }
    
    • Son2.vue通过 mapMutations 映射
    <button @click="setUser({ name: 'xiaoli', age: 80 })">更新个人信息</button>
    <button @click="setTheme('skyblue')">更新主题</button>
    
    methods:{
    // 分模块的映射
    ...mapMutations('setting', ['setTheme']),
    ...mapMutations('user', ['setUser']),
    }
    
(6)使用模块actions方法
  • 注意:默认模块中的 mutation 和 actions 会被挂载到全局,需要开启命名空间,才会挂载到子模块。

  • 使用模块actions方法

    1. 通过 store 调用:$store.dispatch('模块名/xxx ', 额外参数)
    2. 通过 mapActions 映射
      1. 默认根级别的映射:mapActions([ 'xxx' ])
      2. 子模块的映射:mapActions('模块名', ['xxx']) - 需要开启命名空间
  • 代码实现

    • modules/user.js
    const actions = {
          
          
      setUserSecond (context, newUserInfo) {
          
          
        // 将异步在action中进行封装
        setTimeout(() => {
          
          
          // 调用mutation   context上下文,默认提交的就是自己模块的action和mutation
          context.commit('setUser', newUserInfo)
        }, 1000)
      }
    }
    
    • Son1.vue 通过 store 调用
    <button @click="updateUser2">一秒后更新信息</button>
    
    methods:{
        updateUser2 () {
          // 调用action dispatch
          this.$store.dispatch('user/setUserSecond', {
            name: 'xiaohong',
            age: 28
          })
        },
    }
    
    • Son2.vue通过 mapActions 映射
    <button @click="setUserSecond({ name: 'xiaoli', age: 80 })">一秒后更新信息</button>
    
    methods:{
          
          
      ...mapActions('user', ['setUserSecond'])
    }
    

image-20230726162640339

(7)小结
  • 直接使用

    • state --> $store.state.模块名.数据项名

    • getters --> $store.getters[‘模块名/属性名’]

    • mutations --> $store.commit(‘模块名/方法名’, 其他参数)

    • actions --> $store.dispatch(‘模块名/方法名’, 其他参数)

  • 借助辅助方法使用

    • import { mapXxxx, mapXxx } from ‘vuex’

    • …mapState、…mapGetters放computed中;

    • …mapMutations、…mapActions放methods中;

    • …mapXxxx(‘模块名’, [‘数据项|方法’])

    • …mapXxxx(‘模块名’, { 新的名字: 原来的名字 })

8、综合案例-购物车

(1)功能模块分析
  • ① 请求动态渲染购物车,数据存 vuex
  • ② 数字框控件 修改数据
  • 动态计算 总价和总数量

image-20230726163241071

(2)脚手架新建项目

image-20230727112441225

  • 注意:勾选vuex
vue create vue-cart-demo
  • App.vue
<template>
  <div class="app-container">
    <!-- Header 区域 -->
    <cart-header></cart-header>

    <!-- 商品 Item 项组件 -->
    <cart-item></cart-item>
    <cart-item></cart-item>
    <cart-item></cart-item>

    <!-- Foote 区域 -->
    <cart-footer></cart-footer>
  </div>
</template>

<script>
import CartHeader from '@/components/cart-header.vue'
import CartFooter from '@/components/cart-footer.vue'
import CartItem from '@/components/cart-item.vue'

export default {
  name: 'App',
  components: {
    CartHeader,
    CartFooter,
    CartItem
  }
}
</script>

<style lang="less" scoped>
.app-container {
  padding: 50px 0;
  font-size: 14px;
}
</style>
  • main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store'

Vue.config.productionTip = false

new Vue({
    
    
  store,
  render: h => h(App)
}).$mount('#app')
  • store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    
    
  state: {
    
    
  },
  getters: {
    
    
  },
  mutations: {
    
    
  },
  actions: {
    
    
  },
  modules: {
    
    
  }
})
  • components/cart-header.vue
<template>
  <div class="header-container">购物车案例</div>
</template>

<script>
export default {
  name: 'CartHeader'
}
</script>

<style lang="less" scoped>
.header-container {
  height: 50px;
  line-height: 50px;
  font-size: 16px;
  background-color: #42b983;
  text-align: center;
  color: white;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 999;
}
</style>
  • components/cart-footer.vue
<template>
  <div class="footer-container">
    <!-- 中间的合计 -->
    <div>
      <span>共 xxx 件商品,合计:</span>
      <span class="price">¥xxx</span>
    </div>
    <!-- 右侧结算按钮 -->
    <button class="btn btn-success btn-settle">结算</button>
  </div>
</template>

<script>
export default {
  name: 'CartFooter'
}
</script>

<style lang="less" scoped>
.footer-container {
  background-color: white;
  height: 50px;
  border-top: 1px solid #f8f8f8;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 0 10px;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: 999;
}

.price {
  color: red;
  font-size: 13px;
  font-weight: bold;
  margin-right: 10px;
}

.btn-settle {
  height: 30px;
  min-width: 80px;
  margin-right: 20px;
  border-radius: 20px;
  background: #42b983;
  border: none;
  color: white;
}
</style>
  • components/cart-item.vue
<template>
  <div class="goods-container">
    <!-- 左侧图片区域 -->
    <div class="left">
      <img src="https://bluecusliyoupicrep.oss-cn-hangzhou.aliyuncs.com/202307271039546.png" class="avatar" alt="">
    </div>
    <!-- 右侧商品区域 -->
    <div class="right">
      <!-- 标题 -->
      <div class="title">低帮城市休闲户外鞋天然牛皮COOLMAX纤维</div>
      <div class="info">
        <!-- 单价 -->
        <span class="price">¥128</span>
        <div class="btns">
          <!-- 按钮区域 -->
          <button class="btn btn-light">-</button>
          <span class="count">1</span>
          <button class="btn btn-light">+</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CartItem',
  methods: {

  }
}
</script>

<style lang="less" scoped>
.goods-container {
  display: flex;
  padding: 10px;
  + .goods-container {
    border-top: 1px solid #f8f8f8;
  }
  .left {
    .avatar {
      width: 100px;
      height: 100px;
    }
    margin-right: 10px;
  }
  .right {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    flex: 1;
    .title {
      font-weight: bold;
    }
    .info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .price {
        color: red;
        font-weight: bold;
      }
      .btns {
        .count {
          display: inline-block;
          width: 30px;
          text-align: center;
        }
      }
    }
  }
}

.custom-control-label::before,
.custom-control-label::after {
  top: 3.6rem;
}
</style>
(3)构建 cart 购物车模块
  • 新建 store/modules/cart.js
export default {
    
    
  namespaced: true,
  state () {
    
    
    return {
    
    
      list: []
    }
  },
}
  • 挂载到 vuex 仓库上 store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import cart from './modules/cart'

Vue.use(Vuex)

export default new Vuex.Store({
    
    
  modules: {
    
    
    cart
  }
})

export default store
(4)准备后端接口服务
  1. 安装全局工具 json-server (全局工具仅需要安装一次),官网地址:https://www.npmjs.com/package/json-server
npm i json-server  -g
  1. 代码根目录新建一个 db 目录
  2. 在db目录创建文件index.json
{
    
    
    "cart": [{
    
    
            "id": 100001,
            "name": "低帮城市休闲户外鞋天然牛皮COOLMAX纤维",
            "price": 128,
            "count": 5,
            "thumb": "https://bluecusliyoupicrep.oss-cn-hangzhou.aliyuncs.com/202307271039546.png"
        },
        {
    
    
            "id": 100002,
            "name": "网易味央黑猪猪肘330g*1袋",
            "price": 39,
            "count": 10,
            "thumb": "https://bluecusliyoupicrep.oss-cn-hangzhou.aliyuncs.com/202307271039546.png"
        },
        {
    
    
            "id": 100003,
            "name": "KENROLL男女简洁多彩一片式室外拖",
            "price": 128,
            "count": 3,
            "thumb": "https://bluecusliyoupicrep.oss-cn-hangzhou.aliyuncs.com/202307271039546.png"
        },
        {
    
    
            "id": 100004,
            "name": "云音乐定制IN系列intar民谣木吉他",
            "price": 589,
            "count": 1,
            "thumb": "https://bluecusliyoupicrep.oss-cn-hangzhou.aliyuncs.com/202307271039546.png"
        }
    ],
    "friends": [{
    
    
            "id": 1,
            "name": "zs",
            "age": 18
        },
        {
    
    
            "id": 2,
            "name": "ls",
            "age": 19
        },
        {
    
    
            "id": 3,
            "name": "ww",
            "age": 20
        }
    ]
}
  1. 进入 db 目录,执行命令,启动后端接口服务 (使用–watch 参数 可以实时监听 json 文件的修改)
json-server  --watch  index.json
  1. 访问接口测试 http://localhost:3000/cart
(5)请求动态渲染数据

image-20230727112539198

image-20230727105134836

  1. 安装 axios
yarn add axios
  1. 准备actions 和 mutations(store/modules/cart.js
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. 调用 action, 获取数据(App.vue
import { mapState } from 'vuex'

export default {
  name: 'App',
  components: {
    CartHeader,
    CartFooter,
    CartItem
  },
  created () {
    this.$store.dispatch('cart/getList')
  },
  computed: {
    ...mapState('cart', ['list'])
  }
}
  1. 动态渲染(App.vue
<!-- 商品 Item 项组件 -->
<cart-item v-for="item in list" :key="item.id" :item="item"></cart-item>
  • components/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>
(6)修改数量

image-20230727112559032

image-20230727133020899

  1. 注册点击事件(components/cart-item.vue
<!-- 按钮区域 -->
<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(components/cart-item.vue
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函数(store/modules/cart.js
async updateCount (ctx, payload) {
    
    
  await axios.patch('http://localhost:3000/cart/' + payload.id, {
    
    
    count: payload.count
  })
  ctx.commit('updateCount', payload)
}
  1. 提供mutation函数(store/modules/cart.js
mutations: {
    
    
  ...,
  updateCount (state, payload) {
    
    
    const goods = state.list.find((item) => item.id === payload.id)
    goods.count = payload.count
  }
},
(7)底部总价展示

image-20230727145537931

  1. 提供 getters(store/modules/cart.js
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. 动态渲染(components/cart-footer.vue
<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>

猜你喜欢

转载自blog.csdn.net/liyou123456789/article/details/131964540