2_vuex状态管理器

1. 安装

 
  1. $ npm install vuex

2. 使用

1. 新建store文件夹

2. 新建store/index.js文件

核心代码

 
  1. import Vue from 'vue'
  2. import Vuex from 'vuex'
  3. import User from './Modules/User'
  4.  
  5. Vue.use(Vuex)
  6.  
  7. export default new Vuex.Store({
  8.  
  9. modules: {
  10. User
  11. }
  12.  
  13. })

3. 新建Modules/user.js文件 【模块文件,不同模块对应不同文件】

核心代码

 
  1. import NetUtils from '../../common/utils/NetUtils'
  2.  
  3. const state = {
  4. DataList: []
  5. }
  6.  
  7. const mutations = {
  8. PushDataList (state, data) {
  9. state.DataList = data.info
  10. }
  11. }
  12.  
  13. const actions = {
  14. GetDataList ({commit}, data) {
  15. let requestUrl = 'http://happy.dpxiao.com/api/v1/user/getList'
  16. NetUtils.R(requestUrl, null, function (res) {
  17. commit({
  18. type: 'PushDataList',
  19. info: res.data
  20. })
  21. })
  22. }
  23. }
  24.  
  25. export default {
  26. state,
  27. mutations,
  28. actions
  29. }

3. 引入使用

1. main.js文件引入,这里有个重点,store不能修改为其他名称

2. vue使用

核心代码

 
  1. <template>
  2. <div id="testVue">
  3. {{testName}}
  4. </div>
  5. </template>
  6.  
  7. <script>
  8. import { mapState } from 'vuex'
  9. export default {
  10. name: 'testVue',
  11. // 数据初始化
  12. data () {
  13. return {
  14. testName: 'hello world'
  15. }
  16. },
  17. computed: {
  18. ...mapState({
  19. // 获取测试的数据
  20. testValue: state => state.User.DataList
  21. })
  22. },
  23. mounted () {
  24. this.getData()
  25. },
  26. // 方法
  27. methods: {
  28. getData () {
  29. this.$store.dispatch('GetDataList')
  30. }
  31. },
  32. // 监听数据的变化
  33. watch: {
  34. testValue: function (val) {
  35. console.log(val.name)
  36. console.log(val.age)
  37. }
  38. }
  39. }
  40. </script>
  41.  
  42. <style>
  43.  
  44. </style>

猜你喜欢

转载自my.oschina.net/u/3783808/blog/1623210
今日推荐