Vuex项目Example中的源码学习(1)

@

counter

代码跑起来

从github上把代码下载下来(https://github.com/vuejs/vuex)。

npm install

可能会遇到错误如下

puppeteer@4.0.1 install: `node install.js`

可以执行

npm install --ignore-scripts
npm run dev

项目就可以跑起来。通过http://localhost:8080就可以访问到项目。

项目结构

  • counter
    • app.js
    • Counter.vue
    • index.html
    • store.js

项目效果

在这里插入图片描述
项目其实非常简单,就是点击加号数字可以添加,然后可以检测到数字是奇数还是偶数。后面两个按钮,分笔是如果是奇数的加1,另外一个是异步增加数字。

揣测下大概思路

在开始阅读代码之前,不妨大胆的揣测下实现的思路。然后再对照代码,学习改进。

该demo是关于vuex的代码。那么实现不用说一定是vuex来实现的。那么项目实现的大概思路应该是使用一个 vuex的state来记录count,然后再mutations中可以实现一个increment方法和decrement 方法。点击按钮的时候就可以增加或者减少count的值。然后需要一个可以实时监测着count 是技术还是偶数的操作,这个可以用getters来实现。至于后面的两个按钮。第一个可以在mutations中写一个方法来判断并且添加,也可以在actions中增加方法来实现。最后一个按钮是异步的,只能在actions中去实现。根据项目结构,我们应该不难揣测出来vuex的代码记录在store.js中。Counter.vue实现了界面对vuex的数据调用。

具体代码实现

// store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
  count: 0
}

const mutations = {
  increment (state) {
    state.count++
  },
  decrement (state) {
    state.count--
  }
}

const 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)
    })
  }
}


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

export default new Vuex.Store({
  state,
  getters,
  actions,
  mutations
})

在store.js中实现的和我揣测的差别不大。

需要注意的:

  1. 如果把vuex得代码写在分开的类中,然后被其他类引入,我们需要用export default 的语法来实现。
  2. 例子中的代码在actions中有把mutations中的进行了封装。
<template>
  <div id="app">
    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>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'

export default {
  computed: mapGetters([
    'evenOrOdd'
  ]),
  methods: mapActions([
    'increment',
    'decrement',
    'incrementIfOdd',
    'incrementAsync'
  ])
}
</script>

在Counter.vue中实现的对vuex的调用。我们可以学习到如何简单的把actions引入到调用的组件中来。mapGetters和mapActions的使用。

学习到的知识点

  1. 如果把vuex得代码写在分开的类中,然后被其他类引入,我们需要用export default 的语法来实现。
  2. 例子中的代码在actions中有把mutations中的进行了封装。
  3. mapGetters和mapActions的使用。

demo非常简单。入门第一个。

原文地址:https://www.cnblogs.com/bbird/p/14504996.html