Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the state attribute in vuex

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Most people do not understand the knowledge points of this article "how to use the state attribute in vuex", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to use the state attribute in vuex" article.

Introduction to state attribute

The state attribute is used in Vuex to store the shared data between components; that is, we store the shared state between some components mainly in the state property; it uses a single state tree-all application-level states are contained in one object. This also means that each application will contain only one instance of store. A single state tree enables us to directly locate any specific state fragment and easily take a snapshot of the entire current application state in the process of debugging.

The use of state

In HTML, we can omit the this keyword and use $store.state. State name (variable name) to access the stored state in vuex

State.js files extracted by ①

Export default {loadingFlag: true, / / used to save selected category tags changedLableList: [{name: 'headlines', class: 'iconfont icon-jinrishouru', url:' topnews/index'}, {name: 'Apple', class: 'iconfont icon-pingguoapple', url: "apple/index"}, {name:' NBA', class: 'iconfont icon-tiyu-lanqiu', url: "nba/index"} {name: 'starting a business', class: 'iconfont icon-chaxunchuangyebankaitongqingkuang', url: "startup/index"}, {name:' football', class: 'iconfont icon-swticonzuqiu', url: "football/index"}, {name:' sports', class: 'iconfont icon-paobu', url: "tiyu/index"}]}

② imports the state.js file in the index.js file and registers

Import Vue from 'vue'import Vuex from' vuex'import mutations from'. / mutations'import state from'. / state'import actions from'. / actions'import getters from'. / getters'// installation plug-in Vue.use (Vuex) / / create object export default new Vuex.Store ({state, mutations, actions, getters})

③ is used in components

{{item.name}}

In js code, you must use this.$store.state. State name (variable name) to access the state stored in vuex

Computed: {title () {return this.$route.meta.title}, changedLableList () {return this.$store.state.changedLableList}, alternativeLableList () {return this.$store.state.alternativeLableList}}, extension

Why is it used in the computed calculation property of a component that cannot be placed in the data property?

The content in data is initialized only once before the created hook function is triggered, similar to when we write const data = {foo: 123} directly, in which case the value of the property is purely literal, not the so-called [cache] (where is the cache without Cache Miss?) . It is obvious that JS does not update automatically after a literal quantity assignment.

The simplest example:

Let b = 'xxx' / / equivalent to the data in state let a = b / / when data initializes, assign the value of b to ab =' xyz' / / then for the original type, a must still be 'xxx'

In other words, when the content in data depends on changes, the data property does not change (it is designed to preserve local state data for the component). On the other hand, computed is implemented through dependency tracking. When the Vue variable referenced in the evaluation of computed changes, it will trigger the recalculation of computed. So we can use computed to reference the Vuex state variable so that dependency tracking takes effect. Alternatively, it is also a convenient choice to map Vuex state variables to computed through the mapState () method.

State of vuex

State is the basic data in Vuex, and what is stored on state is the so-called state. When we are not using state, we initialize it directly in data. With state, we transfer the data from data to state.

Single state tree

Vuex uses a single state tree, that is, all the state data is contained in one object. That is, if we define an instance of store, then there is only one state in the store instance. State, as a constructor option, defines all the basic state parameters we need.

A single state tree enables us to directly locate any specific state fragment and easily take a snapshot of the entire current application state in the process of debugging.

Get the Vuex status in the Vue component

The easiest way to read state from an store instance is to return a state in a calculated property.

Example:

For example, we define a count property in state and assign it a value of 10. The contents of the file are as follows:

Import Vue from 'vue' / / introduce vueimport Vuex from' vuex' / / introduce vuexVue.use (Vuex) const state = {count: 10} export default new Vuex.Store ({state})

Then create a Counter component and return count in the component, as shown below:

The value of const Counter = {template: `count is: {{count}} `, computed: {count () {return store.state.count / / returns the count status} of the store instance

Whenever the store.state.count changes, the count property is re-fetched and the interface is refreshed.

This mode depends on the global administrator store. If there are too many modules, then every module or page that uses the data in this state will have to introduce store into it, which is really a bit uncomfortable. So here's the solution.

Vuex provides a mechanism to "inject" state from the root component into each subcomponent through the store option:

New Vue ({el:'# app', store, / / Root component injects store instances into all sub-components / / sub-components components: {Counter}, template: ``} through the store option)

The contents of the index.html file for the Vue project are as follows:

Welcome to chivalrous course Island

Finally, we use npm run dev to run the project. The output in the browser is shown in the figure below. If we change the value of count in state, the page will refresh automatically:

MapState auxiliary function

When a component needs to acquire multiple states, declaring these states as computational properties can be repetitive and redundant. To solve this problem, we can use the mapState helper function to help us generate computational properties so that you can press the key a few times less.

Example:

Before using the mapState function, you need to introduce it:

Import {mapState} from 'vuex'

It can be used only after introduction, it can be used in two ways, you can accept an object or an array.

The usage of object is as follows:

Import {mapState} from 'vuex'export default {/ / can be computed: mapState (every property function in a component gets a default parameter state, and then gets its property count directly through state: state = > state.count, / /' count' maps directly to count in the state object, equivalent to this.$store.state.count count: 'count'})}

The array usage is as follows:

/ / when the name of the mapped calculation attribute is the same as the child node name of state, we can also pass an array of strings to mapState. Export default {computed: mapState ([/ / Array 'count'])} above is about "how to use state attributes in vuex". I believe you all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report