1. 安装
$ npm install vuex
2. 使用
1. 新建store文件夹
2. 新建store/index.js文件
核心代码
import Vue from 'vue'
import Vuex from 'vuex'
import User from './Modules/User'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
User
}
})
3. 新建Modules/user.js文件 【模块文件,不同模块对应不同文件】
核心代码
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. 引入使用
1. main.js文件引入,这里有个重点,store不能修改为其他名称
2. vue使用
核心代码
<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>