vuex使用案例(下)

2021-10-08 22:47:13 字數 2845 閱讀 8339

使用computed計算

="hello"

>

hello vuex<

/h1>

}<

/h5>

"$store.commit('jia')"

>

+<

/button>

"$store.commit('jian')"

>

-<

/button>

<

/p>

<

/div>

<

/template>

import

from

'vuex'

export

default

// }

// 方法二 需要引入外部 mapstate

computed:

mapstate()

<

/script>

="hello"

>

hello vuex<

/h1>

}<

/h5>

"jia"

>

+<

/button>

"jian"

>

-<

/button>

<

/p>

<

/div>

<

/template>

import

from

'vuex'

export

default

}<

/script>

getter不能使用箭頭函式,會改變this的指向

在store.js新增getters

// 計算

const getters =

}export

default

newvuex.store()

//count的引數就是上面定義的state物件

//getters中定義的方法名稱和元件中使用的時候一定是一致的,定義的是count方法,使用的時候也用count,保持一致。

元件中使用

import

from

'vuex'

export

default

, methods:

}<

/script>

在store.js新增actions

import vue from

'vue'

import vuex from

'vuex'

vue.

use(vuex)

// 定義常量

const state =

// mutations用來改變store狀態 同步狀態

const mutations =

,jian

(state),}

// 計算屬性

const getters =

}// 非同步狀態

const actions =

,2000

)alert

('我先被執行了,然後兩秒後呼叫jian的方法')}

,jianplus

(context)

}export

default

newvuex.store()

在元件中使用

="hello"

>

hello vuex<

/h1>

}<

/h5>

"jia"

>

+<

/button>

"jian"

>

-<

/button>

<

/p>

"jiaplus"

>

+plus<

/button>

"jianplus"

>

-plus<

/button>

<

/p>

<

/div>

<

/template>

import

from

'vuex'

export

default

, methods:)}

}<

/script>

h5<

/style>

適用於非常大的專案,且狀態很多的情況下使用,便於管理

修改store.js

import vue from

'vue'

import vuex from

'vuex'

vue.

use(vuex)

const state =

const mutations =

,jian

(state),}

const getters =

}const actions =

,2000

)alert

('我先被執行了,然後兩秒後呼叫jian的方法')}

,jianplus

(context)

}//module使用模組組的方式 modulea

const modulea =

// 模組b moduleb

const moduleb =

}export

default

newvuex.store(}

)

vuex案例 豆瓣介面

jsonp使用方法 豆瓣介面位址支援jsonp但是不支援cors。注意 靜態資源 douban static.zip 完整案例 douban vuex.zip main.js import vue from vue import store from store import router from...

Vuex案例 購物車

購物車 demo,帶你理解並使用 vuex 狀態管理 購物車 vuex 中建立兩個模組,分別用來記錄商品列表和購物車的狀態,store 的結構 store modules cart.js production.js index.js 檢視結構 view cart index.vue home ind...

vuex小案例 元件共用資料

將state中的資料做一些集中處理,用map遍歷陣列中每乙個資料做處理 將state作為引數傳入,可以直接使用遍歷等 getters return saleproducts payload作為引數被傳入使用的元件,items.price payload payload傳幾就減幾 mutations ...