Vuex小白學習筆記(一)

目錄

 

簡介

基本對象

如何使用

總結


簡介

vuex是一個爲vue.js應用開發的狀態管理模式

基本對象

  1. state:數據倉庫(類似於data)
  2. getters:對數據獲取之前再次編譯,(類似於computed)
  3. mutations:修改狀態,同步。在組件中使用:$store.commit('',params) (類似於function)
  4. actions:異步操作。在組件中使用:$store.dispatch('',params)

如何使用

  1. 下載vue-cli項目:https://www.jianshu.com/p/5e13bc2eb97c
  2. npm install vuex
  3. 在項目中新建store文件夾=>index.js文件
  4. // index.js
    import Vue from 'vue'//引入vue
    import Vuex from 'vuex'//引入vuex
    //在Vue中使用Vuex
    Vue.use(Vuex)
    
    //創建Vuex實例實例
    const store =new Vuex.Store({
        state:{
            count:1,
            count1:0,
        },
        mutations:{
            add(state,n=0){
                return state.count+=n;
            },
            reduce(state,n=0){
                return state.count-=n
            }
        },
        actions:{
            addFun(context,n){
                return context.commit('add',n)
            },
            reduceFun(context,n){
                return context.commit('reduce',n)
            }
        },
        getters:{
            gettersCount1(state){
                return state.count1+=10
            }
        }
        
    })
    
    //導出store
    export default store;
    //main.js
    import Vue from 'vue'
    import App from './App.vue'
    import store from './store'
    
    Vue.config.productionTip = false
    
    new Vue({
      store,
      render: h => h(App),
    }).$mount('#app')
    

     

總結

  • 如果需通過頁面某個事件改變數據時使用mutation,如果獲取前內部數據進行編譯時使用getter ↵
  • vue中,只有mutation能夠改變state

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章