VUEX综合案例

1、Vuex分成五个部分:

State:单一状态树,共同维护的一个状态,state里面可以是很多个全局状态
Getters:状态获取,获取数据并渲染
Mutations:触发同步事件,处理数据的唯一途径,state的改变或赋值只能在这里
Actions:提交mutation,数据的异步操作
Module:将vuex进行分模块
在这里插入图片描述

2、使用步骤

2.1 安装
npm install vuex -S

2.2 创建store模块,分别维护state/actions/mutations/getters
store文件夹
index.js
state.js
actions.js
mutations.js
getters.js

2.3 在store/index.js文件中新建vuex的store实例,并注册上面引入的各大模块
除了index.js以外其他四个js文件都需要引入下面这个模块
index.js

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import getters from './getters'
import actions from './actions'
import mutations from './mutations'

Vue.use(Vuex)

const store = new Vuex.Store({
     state,
     getters,
     actions,
     mutations
 })

 export default store

2.4 在main.js中导入并使用store实例
main.js

import store from './store'

new Vue({
    el: '#app',
    router,
    store, //在main.js中导入store实例
    components: {
        App
    },
    template: '<App/>',
    data: {
       
    }      
 })

2.5 state.js

export default{
  //定义变量,名字自定义
      htname:'aaa', //后面基本上用的是这个变量
      hhname:'bbb',
}

2.6 mutations.js

export default {
  sethtname: (state, payload) => {
    state.htname = payload.htname;
  },
}

2.7 action.js

export default {
  sethtnameAsync: (context, payload) => {
    console.log('哦哦哦');
    setTimeout(() => {
      console.log('嗯嗯嗯');
      context.commit('sethtname', payload);
    }, 3000);
    console.log('哈哈哈');
  },
  doAjax:(context, payload) => {
    //vuex是不能被vue实例的
    let _this =payload._this;
    let url = this.axios.urls.SYSTEM_USER_DOLOGIN;
    // let url = 'http://localhost:8080/T216_SSH/vue/userAction_login.action';
     console.log(url);
    _this.axios.post(url,{}).then((response) => {
        console.log('doAjax............');
        console.log(response);
      }).catch((response)=>{
        console.log(response);
      });
    },
  }

2.8 getters.js 获取数据并且渲染

export default{
   gethtname: (state) => {
         return state.htname;
     }
}

2.9 显示页面VuePage1.vue

<template>
  <div>
    <h2>第一个vuex页面:</h2>
    <h3>{{ht}}</h3>
    <button @click="hscht">换诗词</button>
    <button @click="hschtAsync">一个月后换诗词</button>
    <button @click="doAjax">测试vuex中使用ajax</button>
  </div>
</template>
<script>
  export default{
    data(){
      return{
      };
    },
    methods: {
      hscht() {
          this.$store.commit('sethtname',{
            htname:'bbb',
          });
      },
       hschtAsync() {
           this.$store.dispatch('sethtnameAsync',{
            htname:'ccc',
          });
      },
      doAjax(){
        this.$store.dispatch('doAjax',{
          _this:this,
        });
      }
    },
    computed: {
      ht() {
        // return this.$store.state.htname;   //不推荐这种方式
        return this.$store.getters.gethtname;
      }
    },
  }
</script>
<style>
</style>
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Vuex 是一个专为 Vue.js 应用程序设计的状态管理模式,它提供了一种集中存储和管理应用状态的方式,特别适合处理像购物车这样的共享组件状态。下面是一个简单的 Vue.jsVuex 购物车案例代码概览: ```javascript // store/index.js import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { cart: [], // 存放商品列表 totalPrice: 0, // 总价格 }, mutations: { addItem(item) { this.cart.push(item) this.totalPrice += item.price }, removeItem(index) { this.cart.splice(index, 1) this.totalPrice -= this.cart[index].price }, updateItem(index, updatedItem) { // 更新指定商品信息 this.cart[index] = updatedItem // 如果价格变化,更新总价 if (updatedItem.price !== this.cart[index].price) { this.totalPrice = this.cart.reduce((sum, product) => sum + product.price, 0) } }, clearCart() { this.cart.length = 0 this.totalPrice = 0 }, }, actions: { addToCart({ commit }, item) { commit('addItem', item) }, removeFromCart({ commit }, index) { commit('removeItem', index) }, // 更多动作(如更新商品或清空购物车) }, getters: { getCartItems(state) { return state.cart }, getTotalPrice(state) { return state.totalPrice }, }, }) ``` 在这个例子中,`store/index.js` 文件定义了购物车的状态、更改这些状态的方法(mutations)、与状态交互的动作(actions)以及用于读取状态的 getter。 在组件中,你可以这样使用这个状态: ```html <template> <div> <ul> <li v-for="(item, index) in cart" :key="index"> {{ item.name }} - {{ item.price }} <button @click="removeFromCart(index)">Remove</button> </li> </ul> <p>Total price: {{ totalPrice }}</p> <button @click="addToCart({ name: 'New Item', price: 10 })">Add to Cart</button> </div> </template> <script> import { mapState, mapActions } from 'vuex' export default { computed: { ...mapState(['getCartItems', 'getTotalPrice']), // 从 store 中获取数据 }, methods: { ...mapActions(['addToCart', 'removeFromCart']), // 调用 action }, } </script> ``` 以上代码展示了一个基础的购物车功能,实际项目中可能还需要添加错误处理、分页、商品详情等复杂功能。相关问题: 1. 在Vue中,为什么要使用Vuex来管理购物车? 2. getters在Vuex中的作用是什么? 3. 这段代码如何处理购物车中的商品数量变化和价格更新?
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值