一个回顾vuex用的代码

  好久没用过vuex了,vuex官方示例的计算器counter是用的webpack打包了单文件组件,不方便回顾,今天把代码改成了html引人的方式,方便回顾

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div id="app">

    </div>

    <script type="text/x-template" id="grid-template">
        <div id="app1">
          Clicked: {{ $store.state.count }} times, count is {{ evenOrOdd }}.
          <button @click="increment">+</button>
          <button @click="decrement">-</button>
          <button @click="incrementIfOdd">Increment if odd</button>
          <button @click="incrementAsync">Increment async</button>
        </div>
    </script>

    <script src="vue.js"></script>
    <script src="vuex.js"></script>


    <script>

        var Counter = {
            template: '#grid-template',
            computed: Vuex.mapGetters([
              'evenOrOdd'
            ]),
            methods: Vuex.mapActions([
              'increment',
              'decrement',
              'incrementIfOdd',
              'incrementAsync'
            ])
        }
        
        const store = new Vuex.Store({
          state: {
            count: 0
          },
          mutations: {
              increment: state => state.count++,
            decrement: state => state.count--
          },
          actions: {
              increment: ({ commit }) => commit('increment'),
              decrement: ({ commit }) => commit('decrement'),
              incrementIfOdd ({ commit, state }) {
                if ((state.count + 1) % 2 === 0) {
                  commit('increment')
                }
              },
              incrementAsync ({ commit }) {
                return new Promise((resolve, reject) => {
                  setTimeout(() => {
                    commit('increment')
                    resolve()
                  }, 1000)
                })
              }
          },

          getters: {
              evenOrOdd: state => state.count % 2 === 0 ? 'even' : 'odd'
          },

        })

        new Vue({
          el: '#app',
          store,
          render: h => h(Counter)
        })
    </script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/zhansu/p/9090967.html