vuex中可以存 各種組件公用的屬性。可以減少接口請求次數。
安裝Vuex
用npm包管理工具,安裝vuex,如果你用vue-cli創建了項目
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>
后面我會接著學習vuex中的公共狀態如何修改
下面接著寫store.js,mutations常量中定義的是用來修改公共狀態的函數
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
})
下面是修改,當在需要修改的地方js中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>
但是,需要說明 的是公共狀態,只有在頁面沒有強制刷新的時候有值,如果刷新頁面你會發現,值不見了,又變成原始定義時候的狀態。所以,當你修改公共狀態的時候要在瀏覽器中存儲一下,以免丟失值。