vuex里面的store架构

将store文件夹分为四个文件夹,分别是actions,getters,mutations,state。

action:和mutatation功能是类似的,都是修改state里面的数据,区别是action用于异步修改

getter:后端传过来的数据,如果需要做一些处理就在getter里面写。

mutations:用于处理同步数据修改

state:存放后端传过来的原生数据。

父组件通过调用action对store里面数据进行了处理,他的子组件只要调用getter就可以获取到父组件处理后的数据

如下是文件结构:

这里我们演示一个小栗子:

state.js

export default{
  count: 0,
  firstName: 'zha',
  lastName: 'lu'
}

getter.js:拼接两个字符串

// 和computer一样,都是对后台返回的数据做处理,只是这个可以应用多个页面

export default {
  fullName (state) {
  const name = state.firstName + state.lastName
  return name
  }
}

mutations.js 执行函数updateCount

// 所有数据的修改都尽量放在mutations,将mutation写成一个对象,它同步操作,不能有异步的代码在里面

export default{
  // 只能有两个参数
  updateCount (state, num) {
  state.count = num
  }
}

actions.js 每隔一段时间提交updateCount

// 和mutations差不多,区别是是action可以存放异步的代码

export default {
    updateCountAsync (store, data) {
    setTimeout(() => (
    store.commit('updateCount', data.num)
    ), data.time)
    }
}

store.js:上面几个都需要在这里进行注册

import Vuex from 'vuex'
import defaultState from './state/state.js'
import mutations from './mutations/mutations'
import getters from './getters/getters.js'
import actions from './actions/actions.js'
// 通过函数,返回一个store
export default () => {
    return new Vuex.Store({
        state: defaultState,
        mutations,
        getters,
        actions
    })
}

App.vue

<template>
  <div id="app">
  <img src="./assets/logo.png">
  <router-link to="/second">second</router-link>
  <router-view/>
{{counter}} {{fullName}}
</div>
</template>

<script>
import {
  mapState,
  mapGetters,
  mapMutations,
  mapActions
} from 'vuex'
export default {
  name: 'App',
  mounted () {
  console.log(this.$store)
  // let i = 1
  // actions异步处理,未使用mapActions
  // this.$store.dispatch('updateCountAsync', {
  // num: 5,
  // time: 2000
  // })
  // 使用mapActions,在调用方法的时候不用传方法名
this.updateCountAsync(
{
  num: 5,
  time: 2000
})
// mutations同步处理,每隔一秒进行count+1
// setInterval(() => {
// this.$store.commit('updateCount', i++)
// }, 1000)
},
computed: {
/* count () {
return this.$store.state.count
},和下面的mapState功能一致 ...要使用命令
npm i babel-preset-stage-1
*/
...mapState({
  // counter: 'count'和下面一样,只是这个是传对象,下面是传方法
  counter: (state) => state.count
}),
...mapGetters(['fullName'])
// 和上面一样fullName () {
// return this.$store.getters.fullName
// }
},
methods: {
  ...mapActions(['updateCountAsync']),
  ...mapMutations(['updateCount'])
  }
}
</script>

<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>

 

posted @ 2019-01-08 11:58  蝴蝶菲菲  阅读(2930)  评论(0编辑  收藏  举报