天天看点

vue Vuex 使用 state getters、mutations、actions、modules

在SPA单页面组件的开发中 Vue的vuex和React的Redux 都统称为同一状态管理,个人的理解是全局状态管理更合适;简单的理解就是你在state中定义了一个数据之后,你可以在所在项目中的任何一个组件里进行获取、进行修改,并且你的修改可以得到全局的响应变更。下面咱们一步一步地剖析下vuex的使用: 

<!DOCTYPE html>
<html >
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="../../ImoocMall/node_modules/vue/dist/vue.js"></script>
  <script src="../../ImoocMall/node_modules/vuex/dist/vuex.js"></script>
  <title>Document</title>
</head>
<body>
  <div id="app">
    <h1>{{msg}}</h1>
    <a href="" target="_blank" rel="external nofollow"  @click.prevent="add">address</a>
    <counter></counter>
  </div>
  <script>
    const counter = {
      template: `
        <div>
          <div>{{count}}</div>
        </div>
      `,
      computed: {
        count () {
          return this.$store.state.modues.count
        }
      }
    }
    const modules = {
      state: {
        count: 0
      },
      getters: {
        increment (state) {
          return state.count + '  hello world'
        }
      },
      mutations: {
        increment (state, result) {
          // 变更状态
          state.count += result
        }
      },
      actions: {
        increment (context, number) {
          context.commit('increment', number)
        }
      }
    }
    const Store = new Vuex.Store({
      modules: {
        modues: modules
      }
    })
    new Vue({
      el: '#app',
      store: Store,
      data: {
        msg: 'vuex'
      },
      components: {
        counter
      },
      mounted () {
        console.log(this.$store.getters.increment)
      },
      methods: {
        add () {
          this.$store.commit('increment', 10)
          this.$store.dispatch('increment', 10)
        }
      }
    })
  </script>
</body>
</html>