1. 程式人生 > >一個demo 理解 vuex

一個demo 理解 vuex

訪問 變更 ebp isp ring 文件 形式 java 容易

相比接觸vue的同學們已經看了官方文檔了。這裏我用一個簡單的demo來闡述下vuex的知識點,雖然簡單,但是容易理解。也加深自己的記憶。

用腳手架建立個項目vue init webpakc-simple ,安裝下vuex,這裏我新建2個組件productOne,productTwo.
好,如果想在2個組件中引用同一組數據,笨方法就是在每個組件的data裏寫上數據,聰明點可以在根組件中建立數據,通過props傳給子組件。那麽這裏,我用vuex來儲存數據。通過在根實例中註冊 store 選項,該 store 實例會註入到根組件下的所有子組件中,且子組件能通過 this.$store 訪問到。

新建個store文件夾,裏面新建個store.js。這裏就是vuex狀態管理作用的地方。
store.js中

import Vue from ‘vue‘
import Vuex from ‘vuex‘

Vue.use(Vuex)

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

main.js中,引入store模塊並註冊。

import Vue from ‘vue‘
import App from ‘./App.vue‘
import {store} from ‘./store/store.js‘
new Vue({
  el: ‘#app‘,
  store,
  render: h => h(App)
})

state

官網上說,state是作為一個單一狀態樹,用一個對象來包含了全部的應用層級狀態。至此它便作為一個唯一數據源的存在。這也意味著,每個應用將僅僅包含一個 store 實例。單一狀態樹讓我們能夠直接地定位任一特定的狀態片段,在調試的過程中也能輕易地取得整個當前應用狀態的快照。

由於vuex的狀態存儲是響應式的,那麽在組件中,我們就可以用計算屬性來獲取state狀態。每當 store.state.count 變化的時候, 都會重新求取計算屬性,並且觸發更新相關聯的 DOM。

import Vue from ‘vue‘
import Vuex from ‘vuex‘

Vue.use(Vuex)

export const store = new Vuex.Store({
    state: {
        products:[
            {name:‘apple‘, price: ‘2‘},
            {name:‘banana‘, price: ‘3‘},
            {name:‘pear‘, price: ‘4‘},
            {name:‘melon‘, price: ‘5‘},
        ]
    }
})

兩個組件中的結構大概如下:用計算屬性用this.$state來返回這個狀態。

<template>
    <div class="product-one">
        <h2>product-one</h2>
        <ul>
            <li v-for="item in product">
                <div class="name">{{item.name}}</div>
                <div class="price">{{item.price}}</div>
            </li>
        </ul>
    </div>
</template>
<script>
    export default {
        computed: {
            product() {
                return this.$store.state.products
            }
        }
    }
</script>

這樣2個組件中的數據就可以統一在store.js中管理了。效果如下:


好,如果現在想改變下數據的一些內容,比如價格都漲2倍,那該怎麽做呢,此時就用到getters

getter

官網上說,getters就相當於是store的計算屬性,可以處理state的數據,它接受第一個參數就是state。那麽接下來就簡單了,把計算邏輯寫在getters裏,在組件中再獲取getters就行了。

import Vue from ‘vue‘
import Vuex from ‘vuex‘

Vue.use(Vuex)

export const store = new Vuex.Store({
    state: {
        products:[
            {name:‘apple‘, price: ‘2‘},
            {name:‘banana‘, price: ‘3‘},
            {name:‘pear‘, price: ‘4‘},
            {name:‘melon‘, price: ‘5‘},
        ]
    },

    getters: {
        changeProduct: (state) => {
            return state.products.map(val => {
                return {
                    name: ‘**‘ + val.name + ‘--‘,
                    price: val.price*2
                }
            })
            return state.products
        }
    }
})

在子組件中,用計算屬性來獲取getters,並在DOM中遍歷這個計算屬性。

    export default {
        computed: {
            product() {
                return this.$store.state.products
            },
            changeProduct(){
                return this.$store.getters.changeProduct
            }
        }
    }

<li v-for="item in changeProduct">
    <div class="name">{{item.name}}</div>
    <div class="price">{{item.price}}</div>
</li>

可以看到,2個組件的數據都改變了。


mutation

更改 Vuex 的 store 中的狀態的唯一方法是提交 mutation。Vuex 中的 mutation 非常類似於事件:每個 mutation 都有一個字符串的 事件類型 (type) 和 一個 回調函數 (handler)。這個回調函數就是我們實際進行狀態更改的地方,並且它會接受 state 作為第一個參數
你不能直接調用一個 mutation handler。這個選項更像是事件註冊:“當觸發一個類型為 increment 的 mutation 時,調用此函數。”要喚醒一個 mutation handler,你需要以相應的 type 調用 store.commit 方法。
簡單來說,就是mutations就類似事件,子組件中用this.$store.commit(‘事件名‘)來獲取。

import Vue from ‘vue‘
import Vuex from ‘vuex‘

Vue.use(Vuex)

export const store = new Vuex.Store({
    state: {
        products:[
            {name:‘apple‘, price: ‘2‘},
            {name:‘banana‘, price: ‘3‘},
            {name:‘pear‘, price: ‘4‘},
            {name:‘melon‘, price: ‘5‘},
        ]
    },

    getters: {
        changeProduct(state){
            return state.products.map(val => {
                return {
                    name: ‘**‘ + val.name + ‘--‘,
                    price: val.price*2
                }
            })
            return state.products
        }
    },

    mutations: {
        decrePrice(state){
            state.products.forEach(val => {
                val.price -= 1
            })
        }
    }
})

子組件中

methods: {
            decrePrice(){
                return this.$store.commit(‘decrePrice‘)
            }
}

action

action和mutation類似,不同的是,Action 提交的是 mutation,而不是直接變更狀態。而且Action支持異步。mutation必須同步執行
Action 函數接受一個與 store 實例具有相同方法和屬性的 context 對象,因此你可以調用 context.commit 提交一個 mutation,或者通過 context.state 和 context.getters 來獲取 state 和 getters。

import Vue from ‘vue‘
import Vuex from ‘vuex‘

Vue.use(Vuex)

export const store = new Vuex.Store({
    state: {
        products:[
            {name:‘apple‘, price: ‘2‘},
            {name:‘banana‘, price: ‘3‘},
            {name:‘pear‘, price: ‘4‘},
            {name:‘melon‘, price: ‘5‘},
        ]
    },

    getters: {
        changeProduct(state){
            return state.products.map(val => {
                return {
                    name: ‘**‘ + val.name + ‘--‘,
                    price: val.price*2
                }
            })
            return state.products
        }
    },

    mutations: {
        decrePrice(state){
            state.products.forEach(val => {
                val.price -= 1
            })
        }
    },

    actions: {
        decrePriceAction(context){
            setTimeout(()=>{
                context.commit(‘decrePrice‘)
            }, 2000)
        }
    }
})

子組件中,用this.$store.dispatch(‘action的名字‘)來獲取。

        methods: {
            decrePrice(){
                // return this.$store.commit(‘decrePrice‘)
                return this.$store.dispatch(‘decrePriceAction‘)
            }
        }

好,一些基本的就這樣,其它的可以去官網看哦~



作者:從小就很瘦
鏈接:https://www.jianshu.com/p/5e6de947d088
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並註明出處。

一個demo 理解 vuex