Vuex 入門到入門

u=2107628671,2584778861&fm=193.jpg

vuex五大核心 1.State 2.Getters 3.Mutations 4.Actions 5.Module 我們項(xiàng)目中需要的都是:state、getters、mutations、actions里面的東西 調(diào)用方法和使用的位置也是有區(qū)別的分別是 不過vuex給我們提供了輔助函數(shù):mapState , mapMutations , mapActions , mapGetters

調(diào)用 方法 輔助函數(shù)
state this.$store.state. xxx mapState
getters this.$store.getters. xxx mapGetters
mutations this.$store.cmmit((xxx) mapMutations
actions this.$store.dispatch(xxx) mapActions

==注意== mapStatemapGetter的使用只能在computed計(jì)算屬性中, mapMutationsmapActions使用的時(shí)候只能在methods中調(diào)用否則報(bào)錯(cuò)

一 、項(xiàng)目引入

1.安裝Vuex到項(xiàng)目中;

npm intsall vuex --save

添加上--save是因?yàn)檫@個(gè)包我們?cè)谏a(chǎn)環(huán)境中是要使用的。

2.創(chuàng)建store文件夾,位置與router同一層級(jí);

添加代碼:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
// 創(chuàng)建Vuex實(shí)列
const store = new Vuex.Store({
  state:{
    count:1,
    name:"張三",
    age:20,
    gender:"男"
  },
  getters:{// 類似vue的computed
    getStateCount:function (state) { // 上面的state
      return state.count+1;
    }
  },
  mutations:{
    add(state){//上面定義的state對(duì)象
      state.count = state.count+1;
    },
    reduction(state){//上面定義的state對(duì)象
      state.count = state.count-1;
    }
  },
  actions:{// 注冊(cè)action。類似vue里的methods
    addFun(context){//接收一個(gè)與store實(shí)列相同的方法
      context.commit("add");
    },
    reductionFun(context){
      context.commit("reduction");
    }
  }
})

export default store

3.引入到main.js文件中;

import store from './store'

new Vue({
  el: '#app',
  store,
  router,
  components: { App },
  template: '<App/>'
})

4.Vuex實(shí)際運(yùn)用;

4.1 關(guān)于states屬性引用

方式一

<h2>{{this.$store.state.count}}</h2>

方式二

<template>
  <div class="home">
    {{nickname}}
  </div>
</template>
<script>
export default {
  name: 'home',
  computed:{
    nickname(){
      return this.$store.state.nickname
    }
  }
}
</script>
computed: mapState({
    count: 'count'
}),
...mapState({
    count: state => state.count,
    name: state => state.name
  })

方式三 - mapState 輔助函數(shù)

<script>
import {mapState} from 'vuex'
export default {
  name: 'home',
  computed: mapState(['nickname','age','gender'])
}
</script>

記住:用mapState等這種輔助函數(shù)的時(shí)候,前面的方法名和獲取的屬性名是一致的。

4.2 關(guān)于getters引用

getters相當(dāng)于vue中的計(jì)算屬性,通過getters進(jìn)一步處理,得到我們想要的值,而且允許傳參,第一個(gè)參數(shù)就是state.

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
 
export default new Vuex.Store({
  state: { //存放狀態(tài)
    nickname:'Simba',
    firstname:'張',
    lastname:'三豐',
    age:20,
    gender:'男',
    money:1000
  },
  getters:{
    realname(state){
      return state.firstname+state.lastname
    },
    money_us(state){
      return (state.money/7).toFixed(2)
    }
  },
  mutations: {},
  actions: {},
  modules: {}
})

Vue部分

方式一:

<h2>我是從Getters的計(jì)算屬性的值:{{this.$store.getters.getStateCount}}</h2>

方式二:使用mapGetter

mapGetter 僅僅是將 store 中的 getter 映射到局部計(jì)算屬性

computed: {  
 ...mapGetters({
 realnameALise: 'realname' // realname 不是字符串,對(duì)應(yīng)的是getter里面的一個(gè)方法名字 然后將這個(gè)方法名字重新取一個(gè)別名 realnameALise
    money_usALise: 'money_us' // money_us 不是字符串,對(duì)應(yīng)的是getter里面的一個(gè)方法名字 然后將這個(gè)方法名字重新取一個(gè)別名 money_usALise
 })
}
4.3 關(guān)于mutation引用

mutations需要通過commit來調(diào)用其里面的方法,它也可以傳入?yún)?shù),第一個(gè)參數(shù)是state,第二個(gè)參數(shù)是載荷(payLoad),也就是額外的參數(shù).

(我們代碼中定義的時(shí)候需要些mutations,它類似于vue中的methods.) 代碼如下:

mutations: { //類似于methods
  addAge(state,payLoad){
     state.age+=payLoad.number
  }
}

template部分

<div class="home">
   <div><button @click="test">測試</button></div>
</div>

js部分

methods:{
 test(){
   this.$store.commit('addAge',{
     number:5
   })
 }
}

調(diào)用的時(shí)候第二個(gè)參數(shù)最好寫成對(duì)象形式,這樣我們就可以傳遞更多信息。

但是,這樣寫還是會(huì)遇到同樣的問題,就是如果需要操作多個(gè)數(shù)據(jù),就會(huì)變的麻煩,這時(shí)候我們就需要mapMutations,通過它將方法映射過來

mapMutations運(yùn)用

mapMutations 其實(shí)跟mapState 的作用是類似的,將組件中的 methods 映射為 store.commit 調(diào)用

methods:{
 ...mapMutations(['addAge'])
}

mapMutations(['addAge'])這一句就相當(dāng)于下面的代碼

addAge(payLoad){
  this.$store.commit('addAge',payLoad)
}

參數(shù)我們可以在調(diào)用這個(gè)方法的時(shí)候?qū)懭?/p>

<button @click="addAge({number:5})">測試</button>
4.4 關(guān)于actions引用

action類似于mutation

但區(qū)別在于:action可以提交mutation

action也不要直接去操作state,而是去操作mutation

action包含異步操作,類似于axios請(qǐng)求,可以都放在action中寫

action中的方法默認(rèn)的就是異步,并且返回promise。舉例代碼如下:

store部分代碼 - 在actions中定義一個(gè)方法:getUserInfo,并且返回一個(gè)對(duì)象

actions: {
  getUserInfo(){
    return {
      nickname:'Simba',
      age:20
    }
  }
}

vue部分

方法一:

created(){
  var res = this.getUserInfo()
  console.log(res)
 
},
methods:{
  ...mapActions(['getUserInfo'])
}
<script>
methods: {

 ...mapMutations({

 totalAlise: 'clickTotal' // clickTotal 是mutation 里的方法,totalAlise是重新定義的一個(gè)別名方法,本組件直接調(diào)用這個(gè)方法

 }),

   ...mapActions({

 blogAdd: 'blogAdd' // 第一個(gè)blogAdd是定義的一個(gè)函數(shù)別名稱,掛載在到this(vue)實(shí)例上,后面一個(gè)blogAdd 才是actions里面函數(shù)方法名稱

 }) 

} } 
</script>

mapActions(['getUserInfo']) 相當(dāng)于以下代碼

getUserInfo(){
  return this.$store.dispatch(‘getUserInfo’)
}

mapActions, action的一個(gè)輔助函數(shù),將組件的 methods 映射為 store.dispatch 調(diào)用

方法二:

store部分:

actions: {
  // 登錄
  Login({ commit }, userInfo) {
    const username = userInfo.username.trim()
    return new Promise((resolve, reject) => {
      login(username, userInfo.password).then(response => {
        const data = response.data
        const tokenStr = data.tokenHead+data.token
        setToken(tokenStr)
        commit('SET_TOKEN', tokenStr)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }
}

vue部分:

  methods: {
    this.$store.dispatch('Login', this.loginForm).then(() => {
       
      }).catch(() => {
      
      }) 
  }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容