Vuejs監(jiān)聽vuex中值的變化的方法示例
比如說,例如,你有一籃子水果,每次你從籃子里添加或拿走水果 ,你想顯示有關水果數(shù)量的信息,但是你也想當籃子中數(shù)量變化的時候收到通知。
fruit-count-component.vue
<template>
<p>Fruits: {{ count }}</p>
</template>
<script>
import basket from '../resources/fruit-basket'
export default () {
computed: {
count () {
return basket.state.fruits.length
// Or return basket.getters.fruitsCount
// (depends on your design decisions).
}
},
watch: {
count (newCount, oldCount) {
// Our fancy notification (2).
console.log(`We have ${newCount} fruits now, yaay!`)
}
}
}
</script>
上述代碼,請注意,watch 對象中函數(shù)名必須和computed對象中的函數(shù)名匹配,在上面實例中名字是 count.
被監(jiān)視屬性的新值和舊值將作為參數(shù)傳遞到監(jiān)視回調(count函數(shù))中。
basket store 看起來像這樣:
fruit-basket.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const basket = new Vuex.Store({
state: {
fruits: []
},
getters: {
fruitsCount (state) {
return state.fruits.length
}
}
// Obvously you would need some mutations and actions,
// but to make example cleaner I'll skip this part.
})
export default basket
您可以在以下資源中閱讀更多內容:
Computed properties and watchers
API docs: computed
API docs: watch
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Vue網(wǎng)頁html轉換PDF(最低兼容ie10)的思路詳解
這篇文章主要介紹了Vue網(wǎng)頁html轉換PDF(最低兼容ie10)的思路詳解,實現(xiàn)此功能需要引入兩個插件,需要的朋友可以參考下2017-08-08
vue-cli3訪問public文件夾靜態(tài)資源報錯的解決方式
這篇文章主要介紹了vue-cli3訪問public文件夾靜態(tài)資源報錯的解決方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
vue項目使用luckyexcel預覽excel表格功能(心路歷程)
這篇文章主要介紹了vue項目使用luckyexcel預覽excel表格,我總共嘗試了2種方法預覽excel,均可實現(xiàn),還發(fā)現(xiàn)一種方法可以實現(xiàn),需要后端配合,叫做KKfileview,本文給大家介紹的非常詳細,需要的朋友可以參考下2023-10-10
???????基于el-table和el-pagination實現(xiàn)數(shù)據(jù)的分頁效果
本文主要介紹了???????基于el-table和el-pagination實現(xiàn)數(shù)據(jù)的分頁效果,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-08-08
vue + vuex todolist的實現(xiàn)示例代碼
這篇文章主要介紹了vue + vuex todolist的實現(xiàn)示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03
vue3中require報錯require is not defined問題及解決
這篇文章主要介紹了vue3中require報錯require is not defined問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06

