Vuex Section 2 state access state object

Vuex Section 2 state access state object


Section 2 state access state object

In Section 1 we have written a const state, this is what we call the access state object , it is the shared value in our SPA (single page application) . Today we mainly learn to assign state objects to internal objects, that is, assign the values ​​in stroe.js to the values ​​in data in our template . For example: will {{$store.state.count}}this form of the kind previously written form: {{count}}.
There are three ways of assignment.

1. Directly assign values ​​through compute attributes of compute

The computed attribute can change the value in the data before output. We use this feature to assign the state value in store.js to the data value in our template.

export default {
    data(){
        return{
            msg:'Hello Vuex'
        }
    },
    computed:{
        count(){
            return this.$store.state.count;  //这里一定要加this,否则找不到$store
        }
    },
    store
}

Then our {{count}} on the Count.vue page can display the count value, which is exactly the same as the previous {{$ store.state.count}} and changes at the same time.

2. Assignment by mapState object

We must first use import to introduce mapState. (Similarly, write it under Count.vue introduction store)

import {mapState} from 'vuex';

Then also write the following code in the computed property:

computed:mapState({
	count:state=>state.count  //这里用ES6的箭头函数来给count传值
}),

It can achieve the same value passing effect.

3. Assignment by array of mapState

Just change the calculated area above:

computed:mapState(['count'])   //数组里面的值是字符串

This is the simplest way to write it, and it is often used in actual project development.

Guess you like

Origin www.cnblogs.com/Elva3zora/p/12714509.html