每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。Vuex 和单纯的全局对象有以下两点不同:
1、Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
2、你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。
下面会以常见的开发流程进行介绍:
1、项目结构
store.js
在src 下创建文件夹store;创建store.js
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'
import actions from './actions'
import getters from './getters'
Vue.use(Vuex)
export default new Vuex.Store({
state,
mutations,
actions,
getters
})
在main.js 导入
接下来,在 main.js里面引入store,然后再全局注入一下,这样一来就可以在任何一个组件里面使用this.$store了:
// 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 App from './App'
import router from './router'
import store from '../src/store/store'
import Axios from 'axios'
Vue.config.productionTip = false
Axios.defaults.baseURL = 'http://upower.work:8080/api'
Vue.prototype.$axios = Axios
Vue.config.devtools = true
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
state.js
export default {
count: 0,
data: []
}
mutations.js
import {ADD, DECREASE, GETLIST} from './mutations-type'
export default {
[ ADD ] (state, data) {
state.count += data
},
[ DECREASE ] (state) {
state.count -= 1
},
[GETLIST] (state, data) {
state.data = data
}
}
mutations-type.js
export const ADD = 'ADD'
export const DECREASE = 'DECREASE'
export const GETLIST = 'GETLIST'
action.js
import {ADD, DECREASE, GETLIST} from './mutations-type'
export default {
add ({commit}, data) {
commit(ADD, data)
},
decrease ({commit}) {
commit(DECREASE)
},
getlist ({commit}, data) {
commit(GETLIST, data)
}
}
Counter.vue
如何使用呢?
<template>
<div>
{{this.count}}
<div v-for="(item,index) in this.data" :key="index">
{{item.title}}
</div>
<div>
<button @click="add">+</button>
<button @click="decrease">-</button>
</div>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
name: 'counter',
data () {
return {
}
},
methods: {
add () {
this.$store.dispatch('add', 2)
},
decrease () {
this.$store.dispatch('decrease')
}
},
computed: {
...mapState(['data', 'count'])
},
mounted () {
const url = '/selectPrescriptionByTitle'
this.$axios.get(url, {params: {title: '神仙'}})
.then(res => {
this.$store.dispatch('getlist', res.data)
console.log(res.data)
})
.catch(res => {
console.log(res)
})
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>