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>
但是,需要说明 的是公共状态,只有在页面没有强制刷新的时候有值,如果刷新页面你会发现,值不见了,又变成原始定义时候的状态。所以,当你修改公共状态的时候要在浏览器中存储一下,以免丢失值。