[Vuex Series] - elaborate on the state of several uses

state is stored in an object store all application state level, mainly to store variable transfer between the components we use every day.

Today we focus on explaining the next several uses state, as to how to start from scratch Vuex project, please see the first article I wrote. Click to view

Use a: Use this $ store.

We still look at an example of how an accumulator, specific codes are as follows:

Adding a count variable in state.js file

const state = {
  count: 0
}
export default state

In the src folder to create a new state folder, and create a new index.vue file, as follows:

<template>
  <div class="state">
    <h2>{{ count }}</h2>
    <button @click="add">+ADD</button>
  </div>
</template>

<script>
export default {
  computed: {
    count () {
      // 第一种用法
      return this.$store.state.count
    }
  },
  methods: {
    add () {
      // 第一种用法
      this.$store.state.count++
    }
  }
}
</script>

Register at Vue root instances the store option, the store instance will be injected into all sub-components under the root component and subassembly through this. $ Store to visit.

Usage of Two: file references store.js

Specific codes are as follows:

state.js reference to the above examples of the contents of the file, to modify state / index.vue, as follows:

<template>
  <div class="state">
    <h2>{{ count }}</h2>
    <button @click="add">+ADD</button>
  </div>
</template>

<script>
import store from '@/store/store.js'
export default {
  computed: {
    count () {
      // 第二种用法
      return store.state.count
    }
  },
  methods: {
    add () {
      // 第二种用法
      store.state.count++
    }
  }
}
</script>

This method Vue modular construction system, the need to import frequently require the use of each component in the state.

Usage 3: Use mapState Helper

Specific codes are as follows:

state.js reference to the above examples of the contents of the file, to modify state / index.vue, as follows:

<template>
  <div class="state">
    <h2>{{ count }}</h2>
  </div>
</template>

<script>
// import store from '@/store/store.js'
import { mapState } from 'vuex'
export default {
  computed: mapState({
    count: state => state.count
  })
}
</script>

or

<template>
  <div class="state">
    <h2>{{ count }}</h2>
  </div>
</template>

<script>
// import store from '@/store/store.js'
import { mapState } from 'vuex'
export default {
  computed: {
    ...mapState(['count'])
  }
}
</script>

When a component needs to obtain multiple states when these states are declared to calculate the property will be some duplication and redundancy. To solve this problem, we can use mapState helpers help us generate calculate property

 

Guess you like

Origin www.cnblogs.com/wangshucheng/p/11203152.html