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 install vue State Management Vuex

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces how to install vue state management Vuex, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.

Installation of vue state management methods: 1, to create a Vue-based project, the implementation of the "npm install" command installation dependency; 2, in the control command line, the implementation of the "npm install vuex-- save" command to install Vuex.

The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.

What is Vuex

Vuex is a state management model developed specifically for Vue.js applications. It uses centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable way. Vuex is also integrated into Vue's official debugging tool devtools extension, providing advanced debugging features such as zero configuration time-travel debugging, status snapshot import and export, and so on.

This status self-management application consists of the following parts:

State, the data source that drives the application

View, declaratively mapping state to views

Actions, responding to state changes caused by user input on the view.

The following is a minimalist representation of the concept of "one-way data flow":

A more complex situation

Multiple views depend on the same state.

Behaviors from different views need to change the same state.

Under what circumstances should I use Vuex?

While Vuex can help us manage shared state, it also comes with more concepts and frameworks. This requires a tradeoff between short-term and long-term benefits.

If you don't plan to develop large single-page applications, using Vuex can be tedious and redundant. That's true-if your application is simple enough, you'd better not use Vuex. A simple global event bus

It will be enough for you. However, if you need to build a medium-to-large single-page application, you are likely to consider how to better manage state outside the component, and Vuex will be a natural choice. To quote Dan Abramov, the author of Redux:

Flux architecture is like glasses: you'll know when you need it.

III. Installation

First, you need to create a Vue-based project, which you can usually do:

# Global installation vue-cli$ npm install-- global vue-cli# creates a new project based on webpack template $vue init webpack my-project# installation dependency, you $cd my-project$ npm install$ npm run dev

Use the npm package management tool to install vuex. Just enter the following command on the control command line.

Npm install vuex-save

It is important to note that-save must be added here, because we need to use your package in the production environment.

By simply relying on the installation operation, the vuex reference is successful, and then we can play as much as we can.

For a simple example, enter the following code in the main.js file:

Import Vue from 'vue'import Vuex from' vuex'Vue.use (Vuex) const store = new Vuex.Store ({state: {count: 0}, mutations: {increment (state) {state.count++}) store.commit ('increment') / * eslint-disable no-new * / new Vue ({el:' # app', template: `

{{count}}

`, computed: {count () {return store.state.count})

After running, you can see that a 1 is displayed on the page, that is, the function increment has been executed correctly, and the count has changed from the initial 0 to 1 output since the addition.

It is important to point out that we submit the mutation rather than directly change the store.state.count because we want to track the state change more clearly.

Usually we don't use it this way, a better way to use it is:

1. Create a new store folder (this is not required), and create a new store.js file under the folder, introducing our vue and vuex into the file.

Import Vue from 'vue';import Vuex from' vuex'

2. In the store.js file, use Vue.use to reference vuex.

Vue.use (Vuex)

3. Introduce the newly created vuex file into main.js

Import store from'. / store/store'

4. Through the store option, Vuex provides a mechanism to "inject" the state from the root component to each subcomponent (you need to call Vue.use (Vuex). By registering the store option in the root instance, the store instance will be injected into all the subcomponents under the root component, and the subcomponents can be accessed through this.$store. :

Import Vue from 'vue'import App from'. / App'import router from'. / router'import store from'. / store/store'Vue.config.productionTip = false/* eslint-disable no-new * / new Vue ({el:'# app', router, store, template:', components: {App}}) IV.

1. Now we add a constant object to the store.js file.

State: {count: 1}

2. Encapsulate the code with export default so that it can be referenced externally.

Export default new Vuex.Store ({name: 'store', state: {count: 1}})

3. Create a new test template for Vue, located in the components folder, with a random name. I call it count.vue here. In the template, we use {{$store.state.count}} to output the value of count (note: since store has been injected into the instance of vue earlier, there is no need to refer to it again).

{{msg}} {{$store.state.count}}

Export default {data () {return {msg: 'Hello Vuex'}}, computed: {count () {return this.$store.state.count}

4. Add two methods to change state in the store.js file.

Mutations: {increment (state) {state.count + = 1}, decrement (state) {state.count-= 1}}

5. Add two buttons to the test.vue template and call the method in mutations.

+-

6. Reference the file in the index.js under the router folder, define the corresponding route, run the program and enter the interface, and click the button to view the effect.

{path:'/ count', name: 'Count', component: Count} 5. State access status object

State, which is what we call the access state object, is the shared value in our SPA (single-page application).

The access state object is assigned to the internal object, that is, the value in stroe.js is assigned to the value in data in our template. There are three ways to assign values

1. Assign values directly through the calculation attribute of computed

The computed attribute can change the value in data before it is output, so we use this feature to assign the state value in store.js to the data value in our template.

Computed: {count () {return this.$store.state.count;}}

What you need to pay attention to here is the sentence return this.$store.state.count. Be sure to write this, or you won't find $store. This way of writing is easy to understand, but it is troublesome to write, so let's take a look at the second way of writing.

2. Assign values through the object of mapState

We will first introduce mapState using import.

Import {mapState} from 'vuex'

Then write the following code in the computed calculation property: (choose a method as needed)

Computed: mapState ({/ / arrow function makes the code more concise count: state = > state.count, / / es6 writing, function (state) {return state.count} / / string parameter 'count' is equivalent to `state.count` countAlias:' count', / / in order to be able to use `this` to get the local state You must use the regular function countPlusLocalState (state) {return state.count + this.localCount}})

3. 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.

Computed: mapState ([/ / Mapping this.count is store.state.count 'count'])

4. You can also use a simplified method (I prefer this method to have the same meaning as the third one, and there is a similar way to write it later in mutations).

/ / use the object expansion operator to mix this object into an external object... mapState ({num: 'count'})

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

Thank you for reading this article carefully. I hope the article "how to install vue status Management Vuex" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

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