3. Simple and practical Store

1, the State

A single state tree that defines the default initial value of the application state from which the data required for the page display is read.

  • VuexWith a single state tree, a single object contains all application-level state. It exists as a “unique data source.” This also means that each app will contain only one Store instance.
  • A single state tree allows us to directly locate any particular state fragment and easily take a snapshot of the entire current application state during debugging.
  • Not directly tostateTo make changes, you need to passMutationMethod to change.

Since Vuex’s state store is reactive, the easiest way to read state from a Store instance is to return some state in a calculated property:

// Create a Counter component
const Counter = {
    computed: {
        count () {
            return store.state.count
        }
    }
}
Copy the code

Every time store.state.count changes, the calculated property is refetched and an update to the associated DOM is triggered.

However, this pattern causes components to rely on global state singletons. In a modular build system, state needs to be imported frequently in each component that needs to use state, and state needs to be simulated when testing components.

Vuex, via the Store option, provides a mechanism to “inject” state from the root component into each child component (by calling vue.use (Vuex)) :

The configuration State

<! Store /index.js -->import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex) // VUE plugin mechanism

const store= new Vuex.Store({
	// Store is the equivalent of data in a component that stores global data
	state: {"name":"Sun Bujian 1208"."age":18
    },
	getters:{
		
	},
	mutations:{
		
	},
	actions:{
		
	},
	modules: {}})export default store
Copy the code

Access to the state

1. Through attribute access, you need to inject store into the root node.

<! Pages /index/index.vue -->
<template>
    <view>
        <text>Username: {{username}}</text>
    </view>
</template>
<script>
    import store from '@/store/index.js';// Need to introduce store
    export default {
        data() {
            return{}},computed: {
            username() {
                return store.state.username 
            }
        }
    }
</script>
Copy the code

2. Use this.$store to access data in state.

<! Pages /index/index.vue -->
<template>
    <view>
        <text>Username: {{username}}</text>
    </view>
</template>
<script>
    export default {
        data() {
            return{}},computed: {
            username() {
                return this.$store.state.username 
            }
        }
    }
</script>
Copy the code

mapState

3. Obtain it through the mapState auxiliary function.

When a component needs to fetch multiple states, it can be repetitive and redundant to declare all those states as computed properties. To solve this problem, we can use the mapState helper function to help us generate calculated properties that will save you from pressing the key:

<! Pages /index/index.vue -->
<template>
    <view>
        <view>Username: {{username}}</view>
        <view>Age: {{age}}</view>
    </view>
</template>
<script>
    import { mapState } from 'vuex'/ / into the mapState
    export default {
        data() {
            return{}},computed: mapState({
            // Get the data arrow function from state to make the code more concise
            username: state= > state.username,
            age: state= > state.age,
        }) 
    }
</script>
Copy the code
  • When the mapping computes the attribute name withstateWith the same child node name, we can also givemapStatePass an array of strings.
<! Pages /index/index.vue -->
<template>
    <view>
        <view>Username: {{username}}</view>
        <view>Age: {{age}}</view>
    </view>
</template>
<script>
    import { mapState } from 'vuex'/ / into the mapState
    export default {
        data() {
            return{}},computed: mapState([
            'username'.// Map this.username to store.state.username
            'age',])}</script>
Copy the code
  • In order to be able to usethisTo get the component’s own data, you must use regular functions.
<! Pages /index/index.vue -->
<template>
    <view>
        <view>Username: {{username}}</view>
        <view>Age: {{age}}</view>
    </view>
</template>
<script>
    import { mapState } from 'vuex'/ / into the mapState
    export default {
        data() {
            return {
                firstName:"Li"}},computed: {
            ...mapState({
                username: function (state) {
                    return this.firstName + ' ' +  state.username 
                },
                age: state= > state.age,
            })
        },
    }
</script>
Copy the code
  • Use the object expansion operator

The mapState function returns an object. Use the object expansion operator to combine multiple objects into one so that we can pass the final object to the computed property. Greatly simplified writing:

<! Pages /index/index.vue -->
<template>
    <view>
        <view>Username: {{username}}</view>
        <view>Age: {{age}}</view>
    </view>
</template>
<script>
    import { mapState } from 'vuex'/ / into the mapState
    export default {
        data() {
            return{}},computed: {
            // Use the object expansion operator to blend this object into an external object. mapState({username: state= > state.username,
                age: state= > state.age,
            })
        },
    }
</script>
Copy the code
const store = new Vuex.Store({
    // State is the equivalent of data in the component, which is used specifically to store shared dataState: {MSG}})Copy the code