This time I will bring you an analysis of the vuex state mapState practical project. What are the precautions for vuex state mapState? The following is a practical case, let's take a look.
First use vue cli to build your own vue project
1.npm i -g vue-cli
2.vue init webpack sell (sell is you Project name)
3. Press Enter all the way (during this process you will be prompted whether to install some dependent packages, such as vue-router, es6 grammar check, etc., select Y/N based on your personal habits or hobbies)
4.npm i (This is the dependency package of the installation project)
5.npm run dev (start your vue project) At this time, if you see the vue logo on the page, it means that your vue project base has been built Completed, then you can delete the useless components
6. Webpack sell does not install vuex by default, so you need to install vuex; press ctrl c twice on the command line to end the server, npm install vuex –save to install vuex.
7. Create a new vue component in your src directory. Let’s name it helloVuex (you can name it as you like, just be happy). This component is mainly used as the main container and only displays content
8. Then create a new one What the hell is the component called (I'll call it the display component here) is used to accept the state in the state
9. Next, we create a new folder called store in the src directory, and create a new js file under the store called test. js (the store here is our front-end data warehouse) uses vuex for state management. Store is the core of vuex, so it is named store. Create a new store file in the src directory, and create a new test.js file in the store directory (as shown below). You can see that before using vuex, you need to tell vue to use it, Vue.use(Vuex); We only have one variable count to manage here, so when creating the store object, pass parameters to the constructor, there is only one count under the state, and Initialized to 0.
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { count: 0 } export default store
Now all the status, that is, the variables are placed in test.js, so how can our component get the status modification value? There are two steps to be performed here
1. Vue provides an injection mechanism, which is to inject our store object into the root instance. The root instance of vue is the new Vue constructor, and then in all subcomponents, this.$store points to the store object. In test.js, we export store and the store has been exposed. new Vue() is in main.js, so we can directly introduce the store in main.js and inject it.
import Vue from 'vue' import App from './App' import router from './router' import store from './store/test' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, store, template: '<app></app>', components: { App } })
2. In child components, use the computed attribute. The computed attribute is automatically updated based on its dependencies. So as long as the state in the store changes, it will automatically change. Make the following changes in display.vue. This.$store in the subcomponent points to the store object. We change the count in test.js to 8, and it becomes 8 on the page.
<template> <p> </p> <h3 id="Count-is-count">Count is {{count}}</h3> </template> <script> export default { computed: { count () { return this.$store.state.count } } } </script>
3. The status value can be obtained through the computed attribute, but every attribute (such as count) in the component is a function. If there are 10, then 10 functions must be written, and 10 must be written repeatedly. It is not very convenient to return this.$store.state all the time. Vue provides the mapState function, which maps state directly to our components.
Of course you must introduce mapState before using it. It can be used in two ways, either accepting an object or an array. Still under the display.vue component.
The object usage is as follows:
<script> import {mapState} from "vuex"; // 引入mapState export default { // 下面这两种写法都可以 computed: mapState({ count: state => state.count // 组件内的每一个属性函数都会获得一个默认参数state, 然后通过state 直接获取它的属性更简洁 count: 'count' // 'count' 直接映射到state 对象中的count, 它相当于 this.$store.state.count, }) } </script>
The array method is as follows:
<script> import {mapState} from "vuex"; export default { computed: mapState([ // 数组 "count" ]) } </script>
4, There is one last question, what if we also have computed properties inside our components? It doesn't belong in mapState. Then we use object segmentation to divide the objects generated by the mapState function into one by one. Just like at the beginning, we listed the calculated attributes one by one. If there are 10 attributes, we will write 10 functions.
The... in es6 is used for splitting, but it can only split arrays. It can split objects in ECMAScript stage-3, so babel-stage-3 is also used at this time; npm install babel-preset-stage-3 --save-dev. After the installation is complete, don’t forget to add babel in babelrc In the configuration file, write stage-3,
, otherwise an error will always be reported. Add a p tag to the page to display the calculation familiarity of our component
babelrc
{ "presets": [ ["env", { "modules": false, "targets": { "browsers": ["> 1%", "last 2 versions", "not ie <p style="text-align: left;">display.vue After the component is changed</p><pre class="brush:php;toolbar:false"><template> <p> </p> <h3 id="Count-is-count">Count is {{count}}</h3> <p>组件自己的内部计算属性 {{ localComputed }}</p> </template> <script> import {mapState} from "vuex"; export default { computed: { localComputed () { return this.count + 10; }, ...mapState({ count: "count" }) } } </script>
put test. Change state.count in js to 10 to see an effect
Let’s take a look at the usage of mapState in Vuex
I encountered a pitfall when using Vuex today. It can also be said to be my own ignorance. After struggling for a long time, I finally discovered the error in my code. It’s really thunderous~~~~~~
index.js
import Vue from 'vue' import Vuex from 'vuex' import mutations from './mutations' import actions from './action' import getters from './getters' Vue.use(Vuex) const state = { userInfo: { phone: 111 }, //用户信息 orderList: [{ orderno: '1111' }], //订单列表 orderDetail: null, //订单产品详情 login: false, //是否登录 } export default new Vuex.Store({ state, getters, actions, mutations, }) computed: { ...mapState([ 'orderList', 'login' ]), }, mounted(){ console.log(typeof orderList); ==>undefind console.log(typeof this.orderList)==>object }
mapState通过扩展运算符将store.state.orderList 映射this.orderList 这个this 很重要,这个映射直接映射到当前Vue的this对象上。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Analysis of vuex state+mapState practical project. For more information, please follow other related articles on the PHP Chinese website!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.