學(xué)習(xí)Vuex

vuex中可以存 各種組件公用的屬性??梢詼p少接口請求次數(shù)。
安裝Vuex
用npm包管理工具,安裝vuex,如果你用vue-cli創(chuàng)建了項目

 npm install vuex --save

然后。在項目中新建一個js文件,命名為store.js,名字隨意哈。
此文件中寫

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);

在main.js中引入新建的store.js文件

import storeconfig from '@/store.js' // 我的文件是放在src文件夾下了

在main.js文件中實例化vue對象的時候加入store

new Vue({
  el: '#app',
  router,
  storeconfig,
  components: { App },
  template: '<App/>'
})

下面接著寫store.js

//增加一個常量變量
const state = {
      count:1
}
//用export default 封裝代碼,讓外部可以引用。
export default new Vuex.Store({
        state
    });

下面是訪問count
在一個vue模板中引入store.js,并在模板中用{{$store.state.count}}輸出count 的值。

<template>
        <div>
            <h2>{{msg}}</h2>
            <hr/>
            <h3>{{$store.state.count}}</h3>
        </div>
    </template>
    <script>
        import store from '@/store'
        export default{
            data(){
                return{
                    msg:'Hello Vuex',

                }
            },
            store //注意這里別忘了加

        }
    </script>

后面我會接著學(xué)習(xí)vuex中的公共狀態(tài)如何修改

下面接著寫store.js,mutations常量中定義的是用來修改公共狀態(tài)的函數(shù)

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
  mid: '', // header中會員ID
  money: 0,
  adminLevel: 0
}

const mutations = {
  changeMid (state, n) {
    state.mid = n
  },
  changeMoney (state, n) {
    state.money = n
  },
  changeAdminLevel (state, n) {
    state.adminLevel = n
  }
}

export default new Vuex.Store({
  state,
  mutations
})

下面是修改,當(dāng)在需要修改的地方j(luò)s中this.$store.commit('changeMoney', res)

<template>
  
</template>
<script>
  import store from '@/store.js'
  export default {
    props: ['money'],
    data () {
      return {
      }
    },
    store,
    methods:{
      change: {
        var aa=100;
        this.$store.commit('changeMoney', aa) // 修改store
      }
      
    }
  }
</script>

但是,需要說明 的是公共狀態(tài),只有在頁面沒有強(qiáng)制刷新的時候有值,如果刷新頁面你會發(fā)現(xiàn),值不見了,又變成原始定義時候的狀態(tài)。所以,當(dāng)你修改公共狀態(tài)的時候要在瀏覽器中存儲一下,以免丟失值。

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

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

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