vuex

main.js

const store = new Vuex.Store({
    //配置
})

new Vue({
    store:store,
    render: h => h(App),
}).$mount('#app')

注意Vuex.Store的Store S大寫

const store = new Vuex.Store({
    state:{
        count:0
    },
    mutations:{
        increase(state){
            state.count++
        },
        decrease(state){
            state.count--
        }
    },
})

state 存放初始狀態(tài)值
mutations 存放改變狀態(tài)的函數(shù)

users.vue

<template>
    <div>
        <p>用戶{{$route.params.id}}</p>
        <p>數(shù)量:{{num}}</p>
        <button @click="add">+1</button>
        <button @click="dec">-1</button>
    </div>
</template>
<script>
    export default{
        computed:{
            num(){
                return this.$store.state.count
            },
        },
        mounted(){
            console.log(this.$route)
        },
        methods:{
            add(){
                this.$store.commit('increase')
            },
            dec(){
                this.$store.commit('decrease')
            },
        }

    }
</script>
  • this.$store.state.count獲取狀態(tài)值
  • this.$store.commit('increase')調(diào)用改變狀態(tài)的函數(shù)

高級用法getters

const store = new Vuex.Store({
    state:{
        list:[2,3,5,8,13,21]
    },
    getters:{
        filterList(state){
            return state.list.filter(item=>item >10)
        }
    }
})
//user.vue
<template>
    <div>
        <p>{{filterList}}</p>
    </div>
</template>
<script>
    export default{
        computed:{
            filterList(){
                return this.$store.getters.filterList
            }
        },
    }
</script>

this.$store.getters.filterList調(diào)用getters里的方法

高級用法actions 操作異步

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • vuex 場景重現(xiàn):一個用戶在注冊頁面注冊了手機(jī)號碼,跳轉(zhuǎn)到登錄頁面也想拿到這個手機(jī)號碼,你可以通過vue的組件化...
    sunny519111閱讀 8,163評論 4 111
  • 安裝 npm npm install vuex --save 在一個模塊化的打包系統(tǒng)中,您必須顯式地通過Vue.u...
    蕭玄辭閱讀 3,049評論 0 7
  • Vuex 的學(xué)習(xí)記錄 資料參考網(wǎng)址Vuex中文官網(wǎng)Vuex項(xiàng)目結(jié)構(gòu)示例 -- 購物車Vuex 通俗版教程N(yùn)uxt....
    流云012閱讀 1,542評論 0 7
  • Vuex 是一個專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲管理應(yīng)用的所有組件的狀態(tài),并以相應(yīng)...
    白水螺絲閱讀 4,797評論 7 61
  • 對于前端工程師來說,性能優(yōu)化是我們需要考慮的一個重要問題,下面介紹幾種我知道的前端性能優(yōu)化方法 1.減少Http請...
    zhangjianli閱讀 179評論 1 2

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