1. Installation
$ npm install vuex
2. Use
1. Create a new store folder
2. Create a new store/index.js file
core code
import Vue from 'vue'
import Vuex from 'vuex'
import User from './Modules/User'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
User
}
})
3. Create a new Modules/user.js file [module file, different modules correspond to different files]
core code
import NetUtils from '../../common/utils/NetUtils'
const state = {
DataList: []
}
const mutations = {
PushDataList (state, data) {
state.DataList = data.info
}
}
const actions = {
GetDataList ({commit}, data) {
let requestUrl = 'http://happy.dpxiao.com/api/v1/user/getList'
NetUtils.R(requestUrl, null, function (res) {
commit({
type: 'PushDataList',
info: res.data
})
})
}
}
export default {
state,
mutations,
actions
}
3. Introduce use
1. The main.js file is introduced. There is an important point here. Store cannot be changed to another name.
2. Vue use
core code
<template>
<div id="testVue">
{{testName}}
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
name: 'testVue',
// 数据初始化
data () {
return {
testName: 'hello world'
}
},
computed: {
...mapState({
// 获取测试的数据
testValue: state => state.User.DataList
})
},
mounted () {
this.getData()
},
// 方法
methods: {
getData () {
this.$store.dispatch('GetDataList')
}
},
// 监听数据的变化
watch: {
testValue: function (val) {
console.log(val.name)
console.log(val.age)
}
}
}
</script>
<style>
</style>