2_vuex state manager

1. Installation

 
  1. $ npm install vuex

2. Use

1. Create a new store folder

2. Create a new store/index.js file

core code

 
  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. Create a new Modules/user.js file [module file, different modules correspond to different files]

core code

 
  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. 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

 
  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>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325935043&siteId=291194637