vuex狀態(tài)管理

vuex

????主要應(yīng)用于vue.js中管理數(shù)據(jù)狀態(tài)的一個庫

????通過創(chuàng)建一個集中的數(shù)據(jù)存儲嵌器,供程序中所有組件訪問

vuex核心概念:state具帮、getters、mutations、actions郊丛、module


一虫给、vuex 安裝引入

1、安裝vuex

npm install vuex --save

2辫封、vue項目中導(dǎo)入vuex

在src目錄下新建store/store.js文件硝枉,在該js文件中引入vuex

//1.引入vuex
import Vue from 'vue'
import Vuex from 'vuex'
//2.使用vuex
Vue.use(Vuex)
//3.創(chuàng)建store數(shù)據(jù)源,提供唯一公共數(shù)據(jù)
const store = new Vuex.Store({
  //state存放公共基礎(chǔ)數(shù)據(jù)
  state:{
  
  },
  //對數(shù)據(jù)的處理
  getters:{
  
  }
//4.向外暴露store數(shù)據(jù)倉庫倦微,這樣其他vue組件才能使用store內(nèi)的數(shù)據(jù)
export default store

3妻味、將store對象掛載到vue實例中

在src/main.js下

//1.引入store
import store from './store/store'

new Vue({
  //2.掛載store對象
  store:store,
})

4、在vue組件中使用store.js內(nèi)的數(shù)據(jù)

????使用computed計算屬性欣福,通過調(diào)用this.$store.state.屬性名责球,獲取到需要的數(shù)據(jù)。

html:
  <div>
    <h2>product-list-one:</h2>
    <ul>
    //2.使用數(shù)據(jù)
      <li v-for="product in products">{{product.name}}--{{product.price}}</li>
    </ul>
  </div>
js:
  computed:{
  //1.獲取store.js中的數(shù)據(jù)
    products(){
      return this.$store.state.products
    },
  }

二拓劝、state:{}

????state 提供唯一的公告數(shù)據(jù)源雏逾,所有共享的數(shù)據(jù)都要統(tǒng)一放到 store 的 state 中進(jìn)行存儲。我們需要保存的數(shù)據(jù)就保存在這里郑临,可以在組件頁面通過 this.$store.state.屬性名來獲取我們定義的數(shù)據(jù)栖博。

組件訪問store中數(shù)據(jù)的兩種方式:

1、this.$store.state.屬性名

store.js中定義數(shù)據(jù)

//1.引入vuex
import Vue from 'vue'
import Vuex from 'vuex'
//2.使用vuex
Vue.use(Vuex)
//3.創(chuàng)建store數(shù)據(jù)源厢洞,提供唯一公共數(shù)據(jù)
const store = new Vuex.Store({
  //state存放公共基礎(chǔ)數(shù)據(jù)
  state:{
    products:[
      {name:'nico',price:380},
      {name:'wukong',price:290},
      {name:'jarvis',price:290},
      {name:'janey',price:401},
    ]
  },
  //對數(shù)據(jù)的處理
  getters:{
  }
//4.向外暴露store數(shù)據(jù)倉庫仇让,這樣其他vue組件才能使用store內(nèi)的數(shù)據(jù)
export default store

vue組件中使用store.js數(shù)據(jù)

html:
  <div>
    <h2>product-list-one:</h2>
    <ul>
    //2.使用數(shù)據(jù)
      <li v-for="product in products">{{product.name}}--{{product.price}}</li>
    </ul>
  </div>
js:
  computed:{
  //1.獲取store.js中的數(shù)據(jù)
    products(){
      return this.$store.state.products
    },
  }

2、將store.js數(shù)據(jù)犀变,映射為當(dāng)前組件的計算屬性

在store.js中定義屬性msg

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

Vue.use(Vuex)

const store = new Vuex.Store({
  state:{
    msg:'映射為計算屬性'
  },
})
export default store

在組件中映射屬性為計算屬性

<template>
  <div>
  //3.使用store中定義的msg屬性
    <span>{{msg}}</span>
  </div>
</template>

<script>
// 1.從 vuex 中按需導(dǎo)入 mapState 函數(shù)
import { mapState } from 'vuex'
export default {
  name: "ProductListOne",
  computed:{
  // 2.將全局?jǐn)?shù)據(jù)妹孙,映射為當(dāng)前組件的計算屬性
    ...mapState(['msg'])// 用...展開運算符把 msg展開在資源屬性里
  }
}
</script>

三、getters:{}

????Getter 用于對 Store 中的數(shù)據(jù)進(jìn)行加工處理形成新的數(shù)據(jù)获枝。不會修改 state 里的源數(shù)據(jù)蠢正,只起到一個包裝器的作用,將 state 里的數(shù)據(jù)變一種形式然后返回出來省店。

① Getter 可以對 Store 中已有的數(shù)據(jù)加工處理之后形成新的數(shù)據(jù)嚣崭,類似Vue的計算屬性笨触。

② Store 中數(shù)據(jù)發(fā)生變化,Getter 包裝出來的數(shù)據(jù)也會跟著變化雹舀。

1芦劣、定義getters:

const store = new Vuex.Store({
  getters: {
  
  }
})

2、getters的兩種使用方式(和state的兩種使用方式相同):

① this.$store.getters.方法名

在store.js中定義方法

const store = new Vuex.Store({
  state:{
    products:[
      {name:'nico',price:380},
      {name:'wukong',price:290},
      {name:'jarvis',price:290},
      {name:'janey',price:401},
    ]
  },
  getters:{
    handleProducts: (state)=>{
      var handleProducts = state.products.map(
        (products)=>{
          return{
            name:'@'+products.name+'',
            price:products.price/2
          }
        }
      )
      return handleProducts
    }
  }
})

在組件計算屬性獲取到使用handleProducts()方法

<template>
  <div>
    <h2>product-list-two:</h2>
    <ul>
    //2.通過計算屬性使用數(shù)據(jù)
      <li v-for="product in handleProducts">{{product.name}}--{{product.price}}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "ProductListTwo",
  computed:{
    products(){
      return this.$store.state.products
    },
    handleProducts(){
    //1.獲取store.js中定義的數(shù)據(jù)處理方法
      return this.$store.getters.handleProducts
    }
  }
}
</script>

或者也可以直接在html中使用

<template>
  <div>
    <h2>product-list-two:</h2>
    <ul>
    //在{{}}中直接通過this.$store.getters.handleProducts獲取到數(shù)據(jù)
      <li v-for="product in this.$store.getters.handleProducts">{{product.name}}--{{product.price}}</li>
    </ul>
  </div>
</template>

② 在組件中映射屬性為計算屬性

在store.js中定義方法handleProducts()

const store = new Vuex.Store({
  state:{
    products:[
      {name:'nico',price:380},
      {name:'wukong',price:290},
      {name:'jarvis',price:290},
      {name:'janey',price:401},
    ]
  },
  getters:{
    handleProducts: (state)=>{
      var handleProducts = state.products.map(
        (products)=>{
          return{
            name:'@'+products.name+'',
            price:products.price/2
          }
        }
      )
      return handleProducts
    }
  }
})

在組件中使用handleProducts()方法

<template>
  <div>
    <h2>product-list-one:</h2>
    <ul>
      <li v-for="product in handleProducts">{{product.name}}--{{product.price}}</li>
    </ul>
  </div>
</template>

<script>
// 1.從 vuex 中按需導(dǎo)入 mapState 函數(shù)
import  {mapState, mapGetters} from 'vuex'
export default {
  name: "ProductListOne",
  // 2.將全局?jǐn)?shù)據(jù)说榆,映射為當(dāng)前組件的計算屬性
  computed:{
    ...mapGetters(['handleProducts'])// 用...展開運算符把 handleProducts展開在資源屬性里
  }
}
</script>

四肥缔、Mutations

????Mutations 用于變更 Store 中的數(shù)據(jù)莱没。嚴(yán)格模式下(strict:true),只有 mutation 里的函數(shù)才有權(quán)利去修改 state 中的數(shù)據(jù)。mutation 非常類似于事件:每個 mutation 都有一個字符串的 事件類型 (type) 和 一個 回調(diào)函數(shù) (handler)承疲。但是府瞄,mutation只允許同步函數(shù)敷矫,不能寫異步的代碼础芍。

①嚴(yán)格模式下(strict:true),只能通過 mutation 變更 Store 數(shù)據(jù)神汹,不可以直接操作 Store 中的數(shù)據(jù)庆捺。

②通過這種方式雖然操作起來稍微繁瑣一些,但是可以集中監(jiān)控所有數(shù)據(jù)的變化屁魏。

1滔以、定義mutations:{}

const store = new Vuex.Store({
  mutations: {
  
    }
  }
})

2、mutations的兩種觸發(fā)方式:(與state蚁堤、getters的兩種觸發(fā)方式一樣)

① this.$store.commit('事件名')

在store.js中定義事件declinePrice

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

Vue.use(Vuex)

const store = new Vuex.Store({
  strict:true,//嚴(yán)格模式下醉者,vuex里的數(shù)據(jù)組件只能通過commit觸發(fā)store里的mutations
  state:{
    products:[
      {name:'nico',price:380},
      {name:'wukong',price:290},
      {name:'jarvis',price:290},
      {name:'janey',price:401},
    ],
  },
  mutations:{
  //1、定義事件declinePrice
    declinePrice: (state)=>{
      state.products.forEach((product)=>{
        product.price--
      })
    }
  }
})

export default store

在vue組件中調(diào)用commit改變store中的數(shù)據(jù)

<template>
  <div>
    <h2>product-list-two:</h2>
    <ul>
      <li v-for="product in products">{{product.name}}--{{product.price}}</li>
    </ul>
    <button @click="declinePrice">decline</button>
  </div>
</template>

<script>
export default {
  name: "ProductListTwo",
  computed:{
    products(){
      return this.$store.state.products
    },
  },
  methods:{
    declinePrice: function (){
    //通過commit調(diào)用函數(shù)披诗,改變store的數(shù)據(jù)
      this.$store.commit('declinePrice')
    }
  }
}
</script>

<style scoped>

</style>

*mutations傳遞參數(shù)

在組件中的代碼:

// 觸發(fā) mutation
methods: {
    handleAdd () {
      this.$store.commit('addN', 3)
    }
}

打開 store/index.js 文件,增加一個 addN:

mutations: {
//形參step接收組件傳的參數(shù)3
    addN (state, step) {
      state.count += step
    }
}

②從 vuex 中按需導(dǎo)入 mapMutations 函數(shù)
在store.js文件中定義declinePrice函數(shù)

const store = new Vuex.Store({
  strict:true,//嚴(yán)格模式下立磁,vuex里的數(shù)據(jù)組件只能通過commit觸發(fā)store里的mutations
  state:{
    products:[
      {name:'nico',price:380},
      {name:'wukong',price:290},
      {name:'jarvis',price:290},
      {name:'janey',price:401},
    ],
  },
  mutations:{
    declinePrice: (state)=>{
      state.products.forEach((product)=>{
        product.price--
      })
    }
  }
})

在組件中使用:

<template>
  <div>
    <h2>product-list-one:</h2>
    <ul>
      <li v-for="product in handleProducts">{{product.name}}--{{product.price}}</li>
    </ul>
    <button @click="declinePrice">decline</button>
  </div>
</template>

<script>
//1.將指定的 mutations 函數(shù)呈队,映射為當(dāng)前組件的 methods 函數(shù)
import {mapGetters,mapMutations} from 'vuex'
export default {
  name: "ProductListOne",
  computed:{
    products(){
      return this.$store.state.products
    },
  },
  methods:{
    ...mapMutations(['declinePrice'])用...展開運算符把declinePrice展開在methods里
  }
}

五、Actions

Actions類似于mutations唱歧,不同在于:

  • Actions提交的是mutations宪摧,而不是直接變更狀態(tài)
  • Actions可以包含任意異步操作

1、定義actions

// 定義 Action
const store = new Vuex.Store({
 actions: {

   }
 }
})

2颅崩、Actions的兩種觸發(fā)方式:

① this.$store.dispatch('方法名')

例子:目的-設(shè)置一個定時器几于,三秒后number自減

在store.js中

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

Vue.use(Vuex)

const store = new Vuex.Store({
  strict:true,//嚴(yán)格模式下,vuex里的數(shù)據(jù)組件只能通過commit觸發(fā)store里的mutations
  state:{
    products:[
      {name:'nico',price:380},
      {name:'wukong',price:290},
      {name:'jarvis',price:290},
      {name:'janey',price:401},
    ],
    msg:'映射為計算屬性'
  },
  getters:{
    handleProducts: (state)=>{
      var handleProducts = state.products.map(
        (products)=>{
          return{
            name:'@'+products.name+'',
            price:products.price/2
          }
        }
      )
      return handleProducts
    }
  },
  mutations:{
    declinePrice: (state)=>{
        state.products.forEach((product)=>{
          product.price--
        })

    }
  },
  actions:{
  //1.定義一個屬性declinePrice沿后,
  //context相當(dāng)與this.$store
    declinePrice:(context)=>{
    //2.定時器三秒后觸發(fā)mutations里面的declinePrice屬性
      setTimeout(()=>{
        context.commit('declinePrice')
      },3000)
    }
  }
})

export default store

在vue組件中

<template>
  <div>
    <h2>product-list-one:</h2>
    <ul>
      <li v-for="product in handleProducts">{{product.name}}--{{product.price}}</li>
    </ul>
    <button @click="declinePrice">decline</button>
  </div>
</template>

<script>
// 1.從 vuex 中按需導(dǎo)入 mapState 函數(shù)
import {mapGetters,mapMutations} from 'vuex'
export default {
  name: "ProductListOne",
  computed:{
    products(){
      return this.$store.state.products
    },
    // 2.將全局?jǐn)?shù)據(jù)沿彭,映射為當(dāng)前組件的計算屬性
    ...mapGetters(['handleProducts'])
  },
  methods:{
  //3.onclick事件,通過this.$store.dispatch('declinePrice')去觸發(fā)store.js中的actions
     declinePrice: function(){
       this.$store.dispatch('declinePrice')
     }
  }
}
</script>

<style scoped>

</style>

②從 vuex 中按需導(dǎo)入 mapActions 函數(shù)

使用方法和state尖滚、getters喉刘、mutations相同

六瞧柔、module

????由于使用單一狀態(tài)樹,應(yīng)用的所有狀態(tài)會集中到一個比較大的對象睦裳。當(dāng)應(yīng)用變得非常復(fù)雜時造锅,store 對象就有可能變得相當(dāng)臃腫。

????為了解決以上問題廉邑,Vuex 允許我們將 store 分割成模塊(module)哥蔚。每個模塊擁有自己的 state、mutation蛛蒙、action肺素、getter、甚至是嵌套子模塊——從上至下進(jìn)行同樣方式的分割:

待續(xù)......

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末宇驾,一起剝皮案震驚了整個濱河市倍靡,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌课舍,老刑警劉巖塌西,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異筝尾,居然都是意外死亡捡需,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進(jìn)店門筹淫,熙熙樓的掌柜王于貴愁眉苦臉地迎上來站辉,“玉大人,你說我怎么就攤上這事损姜∈伟” “怎么了?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵摧阅,是天一觀的道長汰蓉。 經(jīng)常有香客問我,道長棒卷,這世上最難降的妖魔是什么顾孽? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮比规,結(jié)果婚禮上若厚,老公的妹妹穿的比我還像新娘。我一直安慰自己蜒什,他們只是感情好测秸,可當(dāng)我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般乞封。 火紅的嫁衣襯著肌膚如雪做裙。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天肃晚,我揣著相機(jī)與錄音锚贱,去河邊找鬼。 笑死关串,一個胖子當(dāng)著我的面吹牛拧廊,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播晋修,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼吧碾,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了墓卦?” 一聲冷哼從身側(cè)響起倦春,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎落剪,沒想到半個月后睁本,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡忠怖,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年呢堰,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片凡泣。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡枉疼,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出鞋拟,到底是詐尸還是另有隱情骂维,我是刑警寧澤,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布严卖,位于F島的核電站席舍,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏哮笆。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一汰扭、第九天 我趴在偏房一處隱蔽的房頂上張望稠肘。 院中可真熱鬧,春花似錦萝毛、人聲如沸项阴。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽环揽。三九已至略荡,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間歉胶,已是汗流浹背汛兜。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留通今,地道東北人粥谬。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像辫塌,于是被迫代替她去往敵國和親漏策。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,713評論 2 354

推薦閱讀更多精彩內(nèi)容