1. 程式人生 > >vue項目中使用vuex

vue項目中使用vuex

nbsp 想要 color class 重新 render 調用 們的 使用

1、運行

cnpm i vuex -S

2、導入包

import Vuex from ‘vuex‘

3、註冊vuex到vue中

Vue.use(vuex)

4、

var  store  = new Vuex.Store({
   state:{
     count: 0         
    },
    munctions: {
       setCount:(state , count)=>{
         state.count  = count
       }
     },
    getters:{
       
// 註意:這裏的 getters , 只負責 對外提供數據,不負責 修改數據,如果想要修改則去munctions optCount:(state) =>{ return ‘當前最新的count值是:‘+ state.count } // 經過咋們的回顧對比,發現 getter 中的方法,和組件中的過濾器比較類似因為過濾器和getters 都沒有修改原來數據 都是把原來的數據做了一層包裝,提供給 調用者 //其次 getters 也和 computed 比較像,只要state 中的數據發什麽了變化 如果getters正好也引用了這個數據,那麽就會立即觸發 getters 的重新求值 ;
} })

import App from ‘./App.vue‘

const vm new Vue({
  el: ‘#app‘,
  render: c=>c(App),
  store //5、將 vuex 創建的 store 掛載到你vm 實例上,只要掛載到了vm 上 任何組件才都能使用store 來讀取數據
})

總結:

1、state中的數據,不能直接修改,如果想要修改,必須通過 munctions

2、如果組件想要直接從 state 上獲取數據:需要 this.$store.state.****

3、如果組件,想要修改數據,必須使用 munctions 提供的方法,需要通過 this.$store.commit(‘方法名稱,唯一的一個參數‘)

4、如果 store 中的state 上的數據,在對外提供的時候,需要做一層包裝,那麽,推薦使用 getters,如果需要使用 getters ,則用 this.$store.getters.***

vue項目中使用vuex