vuex详解

24 篇文章 0 订阅
20 篇文章 0 订阅

1.组件内可以直接修改State数据,但是这样子改的话,devtools无法记录是哪个组件修改的State数据,对后期的调试非常不友好;因此需要通过actions,mutations对vuex做修改;

2.可以在组件内直接通过mutations对state数据进行修改,如果是异步的话无法通过跟踪mutation获取devtools记录,所以异步的话需要actions,再mutations来修改state内数据;

3.mutations提交数据

//目录:store/index.js
state: {
    counter : 1000,
    movies : [
      {mName : '无极',price : 20},
      {mName : '阿甘正传', price : 30},
      {mName : '1900', price : 40},
      {mName : '美丽心灵', price : 50}
    ]
  },
  mutations: {
    increment(state){
      state.counter++
    },
    decrement(state){
      state.counter--
    },
    //普通提交风格
    incrementParam(state,param){
      state.counter+=param
    },
    //特殊提交风格
    incrementParam2(state,payload){
      console.log(payload);
      state.counter+=payload.param
    },
    pushMovies(state,obj){
      state.movies.push(obj)
    },
    yxMut(state){
      state.yx.player="梁朝伟"
      //往state对象数据内添加属性
      state.yx.player2="张曼玉"
      //删除state对象数据内属性
      delete state.yx.player
    }
  },

//组件内调用
add(){
   this.$store.commit("increment")
},
multi(){
  this.$store.commit("decrement")
},
addParam(param){
  //普通提交风格
  this.$store.commit("incrementParam",param)
},
addParam2(param){
  //特殊提交风格
  this.$store.commit({
     type : "incrementParam2",
     param,
     param2 : '无极'
  })
},
//传递多个参数,将参数封装到对象中
addMovies(){
   let obj={mName : '末代皇帝',price:10 }
   this.$store.commit("pushMovies",obj)
}

4.mutation的类型常量

//路径: store/mutation-types.js
export const TEST="test"

//路径:store/index.js
import { TEST } from "./mutation-types"
mutations: {
    [TEST](state){
      console.log("dosomething");
    }
}

//组件内调用
import { TEST } from "./store/mutation-types"
click(){
   this.$store.commit(TEST)
}

5.getters基本用法

类似于computed:

//目录路径:store/index.js
export default createStore({
  state: {
    counter : 1000
  },
  getters : {
    counterPow(state){
      return state.counter*state.counter
    },
    moviesFilter(state){
      return state.movies.filter(s=>s.price<=30)
    },
    //调用getters的方法
    moviesFilterLen(state,getters){
      return getters.moviesFilter.length
    },
    //往getters函数传参
    priceFilter(state){
      return function(price){
        return state.movies.filter(s=>s.price>price)
      }
    }
  },
})
//组件内调用
<h4>getters : {{ $store.getters.counterPow }}</h4>
<h4>myMovies : {{ $store.getters.moviesFilter }}</h4>
<h4>个数:{{ $store.getters.moviesFilterLen }}</h4>
<h4>priceFilter : {{ $store.getters.priceFilter(25) }}</h4>

6.actions基本使用

//目录路径:store/index.js
export default createStore({
  state: {
    info : "星际穿越"
  },
  mutations: {
    updateInfo(state,payload){
      state.info=payload.name
    }
  },
  actions: {
    aUpdateInfo(context,payload){
      return new Promise((resolve,reject)=>{
        setTimeout(()=>{
          context.commit("updateInfo",payload)
          resolve("执行成功")
        },1000)
      })
    }
  },
})

//组件内调用
change(){
      this.$store.dispatch("aUpdateInfo",{name : '金刚川'}).then((res)=>{
        console.log(res);
      })
    },

7.modules分模块

const moduleA={
  state : {
    info : '敦刻尔克'
  },
  mutations : {
    updateInfoA(state,payload){
      state.info=payload.name
    }
  },
  //modules内的actions有作用域,只能调用模块内的mutations
  actions : {
    maUpdateInfo(context,payload){
      setTimeout(()=>{
        context.commit("updateInfoA",payload)
      },1000)
    }
  },
  getters : {
    players(state){
      return state.info+":吴京"
    },
    players2(state,getters){
      return getters.players+",段奕宏"
    },
    players3(state,getters,rootState){
      console.log(rootState);
      return getters.players2+","+rootState.player
    }
  },
}

//根模块内
modules: {
    a : moduleA
  }

//组件内调用
change2(){
   this.$store.commit("updateInfoA",{name : '长津湖'})
},
change3(){
   this.$store.dispatch("maUpdateInfo",{name : '无间道'})
}

8.vuex目录结构分割

import mutations from './mutations'
import moduleA from './modules/moduleA'
import actions from './actions'
const state={
  info : "星际穿越",
  player : '张涵予'
}

export default createStore({
  state: state,
  mutations: mutations,
  actions: actions,
  modules: {
    a : moduleA
  }
})

9.mapGetters使用

遍历出getters,转换成计算属性使用

import { mapGetters } from "vuex"
computed : {
        //方式一
        //...mapGetters(["cartLen","cartList"])     

        //方式二   
        ...mapGetters({
            len : "cartLen",
            list : 'cartList'
        })
    }

10.mapActions使用

遍历出actions,转换成methods方法

methods : {
        //方式一
        //...mapActions(["addCartList"]),

        //方式二
        ...mapActions({
            addCartList : 'addCartList'
        }),
}



//调用
addCart(){
       this.addCartList(this.goodsDetailData).then(res=>{
       console.log(res);
   })
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue.js是一个流行的JavaScript框架,它允许您构建动态Web应用程序。Vuex是一个专为Vue.js应用程序开发的状态管理模式。它允许您在应用程序管理和维护状态,例如用户信息、购物车、主题等。Vuex将状态存储在一个集的存储库,称为store。Vuex的核心概念包括state、mutations、actions和getters。 - state:存储应用程序级别的状态,可以通过store.state访问。 - mutations:用于更改状态的函数,必须是同步函数。可以通过store.commit方法调用。 - actions:用于处理异步操作的函数,可以包含任意异步操作。可以通过store.dispatch方法调用。 - getters:用于从store获取状态的函数,可以通过store.getters访问。 下面是一个简单的示例,演示如何在Vue.js应用程序使用Vuex: 1.安装Vuex ```shell npm install vuex --save ``` 2.创建store ```javascript 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: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }, getters: { getCount: state => { return state.count } } }) export default store ``` 3.在Vue组件使用store ```javascript <template> <div> <p>Count: {{ count }}</p> <button @click="increment">Increment</button> <button @click="incrementAsync">Increment Async</button> </div> </template> <script> import { mapGetters, mapActions } from 'vuex' export default { computed: { ...mapGetters([ 'getCount' ]) }, methods: { ...mapActions([ 'increment', 'incrementAsync' ]) } } </script> ``` 在上面的示例,我们创建了一个名为count的状态,并定义了一个名为increment的mutation和一个名为incrementAsync的action。我们还定义了一个名为getCount的getter,用于从store获取count状态。在Vue组件,我们使用mapGetters和mapActions帮助程序将getter和action映射到组件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

y_w_x_k

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值