首先我们要在自己的vue项目里面使用vuex,就得安装vuex的包,在webstorm里面按alt+F12,打开命令行控制台,输入:
cnpm i vuex -S,执行完毕就可以使用vuex进行项目数据的状态管理了。在router文件夹的同级目录创建store文件夹,里面创建store.js文件,引入vue包。
vuex核心就是store对象,store是一个单项数据流,store里面包含三个模块,一个是state,一个是action,一个是mutations。vuex是一个状态管理器,管理这个整个项目的界面数据。
state对象里面存储项目里面的数据属性值,如果要修改数据,调用mutations对象里面的函数,函数的参数至少有一个state属性,我们通过提交mutation里面的函数就可以对state里面的数据进行修改。
下面是一个让count自动每秒自动加一的demo
store.js如下:
import Vuex from 'vuex'
// 通过函数,返回一个store
export default () => {
return new Vuex.Store({
state: {
count: 0
},
mutations: {
updateCount (state, num) {
state.count = num
}
},
computer: {
count () {
return this.$store.state.count
}
}
})
}
main.js如下
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import Vuex from 'vuex'
import App from './App'
import router from './router'
import createStore from './store/store'
Vue.config.productionTip = false
Vue.use(Vuex)
const store = createStore()
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
router,
components: { App },
template: '<App/>'
})
入口App.vue文件如下
<template>
<div id="app">
<img src="./assets/logo.png">
<router-link to="/second">second</router-link>
<router-view/>
{{count}}
</div>
</template>
<script>
export default {
name: 'App',
mounted () {
console.log(this.$store)
let i = 1
// 每隔一秒进行count+1
setInterval(() => {
this.$store.commit('updateCount', i++)
}, 1000)
},
computed: {
count () {
return this.$store.state.count
}
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
实现的结果:
项目地址见https://github.com/zhangluyou/vue.git/vuexdemo