码迷,mamicode.com
首页 > 其他好文 > 详细

一个回顾vuex用的代码

时间:2018-05-25 23:35:08      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:button   一个   pre   代码   reject   har   char   img   图片   

  好久没用过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>

技术分享图片

 

一个回顾vuex用的代码

标签:button   一个   pre   代码   reject   har   char   img   图片   

原文地址:https://www.cnblogs.com/zhansu/p/9090967.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!