vuex vue狀態管理

第一步安裝vuex(安裝在生產環境)vue

npm install vuex

第二步 src下新建store文件夾 用來專門放狀態管理,store文件夾下新建四個js文件 index.js  actions.js  mutations.js getters.js(後面會一一介紹這幾個文件的做用)vuex

第三步 main.js中引入storenpm

import store from './store'

main.js中實例化的時候使用storeapp

new Vue({
   el:'#app',
   store,//掛載stroe
   router,
   template:'<App>'   ,
   components:{App}      
})

基礎工做作完了,能夠開始第一個demo了this

vuex共分四個模塊,components即組件,數據展現修改層面,actions業務處理事務轉發,mutations具體的業務邏輯處理,getters拿處處理好後的數據返給componentsspa

四個模塊能夠都寫在index.js裏也能夠單獨寫,而後在index.js裏引入,這裏是單獨寫再引入的code

index.jscomponent

import Vue from 'vue'//引入vue
import Vuex from 'vuex'//引入vuex

import * as actions from './actions'
import * as mutations from './mutations'
import * as getters from './getters' //*即全部

Vue.use(Vuex)

    onst state = {
  number:123  
}

//註冊上面各個模塊
const store = new Vuex.Stroe({
   state,getters,actions,mutations 
})

expoort default store

state{}數據存放位置,如今裏面有個number數據爲123router

其實如今已經能夠在組件裏面用這個數據了,經過this.$store.state.number 只是官方不建議這麼用blog

從頁面開始

componentsA.vue

<template>
    <div>
        <p>vuex中的數據{{number}}</p>
       <button @click='modifynumber'>修改number</button>
    </div>
</template>
<script>
    import{mapActions,mapGetters} from 'vuex' // 語法糖
     //mapActions 至關於this.$store.dispatch('請求類型',數據) 發送請求
    //mapGetters 至關於this.$store.getters.number

    export default{
        data(){
          retrun{
                
            }  
        },
        methods:{
           ...mapActions(
                  ['modifynumber']//提交方法  
                ), 
            
        },
        computed:{
          ...mapGetters(['number'])  //獲取state中的數據
        }
    }    
</script>

mapActions寫在methods中  mapGetters寫在computed中

mutations中作具體的業務邏輯處理

mutations.js

export const modifynumber = (state) =>{
  state.number ++  
}

getters.js

export const number = (state) =>{ return state.number}

 大概就是這些了

I love three things in the world: the sun, the moon, and you. The sun for day, the moon for night, and you forever. 

浮世萬千,吾愛有三,日 月  與卿,日爲朝,月爲暮,卿爲朝朝暮暮。

相關文章
相關標籤/搜索