state and getters of Vuex

General usage of store

It's not good to write directly in the new Vuex.store option. The normal way is

create a file

Create client/store/state/

Create client/store/state/state.js

Create client / store / transitions/

Create client / store / state / transitions.js

Module write

// state.js data
export default {
  count: 0
}
// mutations.js operation
export default {
  updateCount (state, num) {
    state.count = num
  }
}

Main entrance introduction

// store.js
import Vuex from 'vuex'

import defaultState from './state/state'
import mutations from './mutations/mutations'

export default () => {
  return new Vuex.Store({
    state: defaultState, // Because there is server-side rendering, when rendering, some data will be sent to the client, which is the operation of overwriting data, so defaultState is only the default state, not the real state.
    mutations // es6 features, abbreviated; operations are interlinked and do not need to be marked with default
  })
}

getters

Getters are similar to computed components in that it is convenient to directly generate some data that can be used directly. When the assembled data is to be used in multiple pages, getters can be used.

Create folders and files

Create client/store/getters/

Create client/store/state/getters.js

Declare getters

// getters.js
export default {
  fullName (state) {
    return `${state.firstName} ${state.lastName}`
  }
}

Introducing getters

// store.js
import Vuex from 'vuex'

import defaultState from './state/state'
import mutations from './mutations/mutations'
import getters from './getters/getters' // Here

export default () => {
  return new Vuex.Store({
    state: defaultState, 
    mutations, 
    getters // Here
  })
}

Using getters

// app.vue
<template>
  <div id="app">
    <p>{{fullName}}</p>
  </div>
</template>

<script>
export default {
  computed: {
    fullName () {
      return this.$store.getters.fullName
    }
  }
}
</script>

Shorthand help method

babel does not support Unwritten grammar

Install babel-preset-stage-1

npm i babel-preset-stage-1 -D

The highest level.

// .babelrc
{
  "presets": [
    "env",
    "stage-1" // Add configuration
  ],
  "plugins": [
    "transform-vue-jsx",
    "syntax-dynamic-import"
  ]
}

mapState shorthand

// app.vue
<template>
  <div id="app">
    <p>{{fullName}} {{count}}</p>
  </div>
</template>

<script>
import {
  mapState
  // mapGetters
} from 'vuex'

export default {
  computed: {
    ...mapState(['count']), // Array with the same name
    fullName () {
      return this.$store.getters.fullName
    }
  }
}
</script>

If the name is different, use the object

...mapState({
      counter: 'count'
    }),

Or function

...mapState({
      counter: (state) => state.count
    }),

mapGetters

Similar to mapState

...mapGetters(['fullName'])

Tags: Vue npm

Posted on Mon, 06 Jan 2020 19:42:18 -0800 by gunslinger008