search
HomeWeb Front-endJS TutorialVue's parent-child components, parent-child component value transfer and a brief analysis of vuex

This article mainly introduces the parent-child components of Vue, a brief analysis of parent-child component value transfer and vuex. It has a certain reference value. Now I share it with you. Friends in need can refer to it

1. How to transfer values ​​​​between the parent and child components of Vue?
First of all, what needs to be said is that since vue has two-way binding, why is there a value transfer problem between parent and child components? This problem is also simple. The components of Vue will be called by other Vue pages. If the arrays are two-way bound, it will be easy to get confused. For example, pages a and b are bound to a num=10, and then pages b and c are bound to each other. If num=5 is tied, who does the num of the vue instance listen to? So, this is why the vue official website says that the data between components can only be circulated in a single item, and it is passed from the parent component to the child component.
Okay, not much to say next. , how do parent-child components transfer values, and who is the parent and who is the child? Example 1: First write a component and put it in the component folder called son.vue (a bit of a spoiler naming...)

<template>
  <p>
    <button>+</button>
    <button>-</button>
    </p>
<p>这里是son的num:{{num}}</p>
  
</template>
<script>
export default {
  //props:["num"],//接收父组件传递过来的值,这里我先写上
  data () {
    return {
        num:0
    }
  },
   methods:{
       add(){//es6的语法相当于add:function(){}
           this.num++;
       },
       minu(){
           this.num--;
       }
   }
}
</script>

I believe everyone can see this component of son.vue Understand, add and subtract the components of num. Next, write an index.vue to call son.vue
//index.vue
<template>
  <p>
    <son></son>//传递一个值给son.vue,这时候可以把son.vue的props那个注释注销掉了
    </p>
<p>这里是index的num:{{num}}</p>
  
</template>
<script>
import son from &#39;./../components/son&#39; 
export default {
  data () {
    return {
      num:10
    }
  },
  components:{
       son
     }
}
</script>

At this time, both nums are 10. Click the add and subtract button again, and we will find that the ‘num of son’ keeps changing, while the ‘num of index’ is always 10. This is the single-item circulation of data. So how do we click the button and change the 'num of index'? At this time, $emit needs to work.

We need to change the code in index.vue

First:

<son></son>//v-on:add="icr"就是绑定一个自定义事件

Add
methods:{
   icr(){
       this.num++;
   },
   der(){
       this.num--;
   }
}

Then the methods in son.vue become

methods:{
   add(){
       this.$emit("add");//$emit("add")就是触发父组件中的add方法
   },
   minu(){
       this.$emit("minu");
   }
}

So,

$emit("xxx") triggers the function of the parent component, changes the num value of the parent component's data, and the parent component passes the value to the child component through props. This enables data transfer and parent-child component communication

. This is the complete code of son.vue and index.vue

//son.vue
<template>
<p>
    <button>+</button>
    <button>-</button>
    </p>
<p>这里是{{num}}</p>

</template>
<script>
export default {
  props:["num"],
  data () {
    return {
        num:10
    }
  },
   methods:{
       add(){
           this.$emit("add");
       },
       minu(){
           this.$emit("minu");
       }
   }
}
</script>

//index.vue
<template>
 <p>
    <son></son>
    </p>
<p>父{{num}}</p>

</template>
<script>
import son from &#39;./../components/son&#39;
export default {
  data () {
    return {
      num:10
    }
  },
  components:{
       son
   },
   methods:{
       icr(){
           this.num++;
       },
       der(){
           this.num--;
       }
   }
}
</script>

2. Let’s talk about vuex and its state, actions, getters, mutations, modules, and store

First of all, the vuex official website says it is a vue state management tool. The state may be difficult to understand. You can simply understand the state as a variable in vue's data. When the data variable relationship between components becomes more complicated, the variables are extracted and managed. You can just take a look at the above to see if the communication between num between the parent and child components is more troublesome. You still need to use $emit to change the data. It would be great if there was a place that stored the value of num just like a warehouse, and whoever wanted to use it could request the value of num, and whoever wanted to change it could change it, right? That's what vuex does, it's a bit like a global variable. If you need to get any components or change something, you can come to him.
1. First of all, state is the only data carrier, just like the warehouse.

2. Mutations are the only things that can change the value of state, use commit, etc.

These two are the most basic and indispensable for vuex. For simple vuex management, just use these two. How to use vuex? See here https://segmentfault.com/a/11...
3. The official description of getters: Derive a new state, which is difficult to understand. To put it simply, it is
filtering and combination!
For example, if there is an array stored in the state, the array contains many data, and I only want to use the ones with status: 0, I can use getters. Doesn't it mean a bit of filtering? So getters are sometimes useful and necessary! . 4. Actions are used to submit mutations, wtf? Why does it feel so redundant! Actually no, the most important thing about this actions is that it can include asynchronous operations. I won’t demonstrate how to operate asynchronously, because you may not use it in many situations.
5. Modules are also auxiliary methods. For example, modulesA has a complete state, actions, getters, and mutations; modulesB can also have a complete state, actions, getters, and mutations. It divides the store into modules to avoid confusion.

Okay, let’s talk about this today. You still need to read more official website documents and practice more. I beg you all for guidance! Learning is really difficult, please guide me...

Finally, if the article is helpful to you, please give me a star to encourage me. I haven't worked yet. . . Wuwuwu

<script>
import son from &#39;./../components/son&#39;
export default {
  data () {
    return {
      num:10
    }
  },
  components:{
       son
   },
   methods:{
       icr(){
           this.num++;
       },
       der(){
           this.num--;
       }
   }
}
</script>

二、说说vuex以及他的state、actions、getters、mutations、modules、store
首先,vuex官网上说是一个vue的状态管理工具。可能状态比较难理解,大家可以简单地把状态理解成为vue的data里面的变量。当组件之间的data变量关系复杂一点的时候,就把其中的变量抽离出来管理。刚好大家可以看看上面,父子组件之间的num之间的通信是不是比较麻烦,改变数据还要用$emit。如果有一个地方跟仓库一样就存放着num的值,谁要用谁去请求num的值,谁想改就改该多好是吧,vuex就是干这个的,有点全局变量的意思。任何组件需要拿,改东西,都可以找他。

1、首先state是惟一的数据载体,跟仓库一样。
2、而mutations是唯一可以改变state的值的东东,使用commit等。
这两个是vuex最最基础缺一不可的。简单的vuex管理就使用这两个就行,如何使用vuex?看这里https://segmentfault.com/a/11...
3、getters的官方说明:派生出新的状态,这个比较难理解。简单来说,就是过滤,组合!
比如说state里面存了一个数组,数组有好多个数据,而我只想要用status:0的那些个,就可以用getters。是不是有点过滤的意思。所以getters有时候还很好用,很必要!。
4、actions是用来提交mutations,wtf?怎么感觉那么多余!其实不是的,这个actions最重要的是可以包含异步操作。如何异步操作就不演示了,因为大家可能很多情况都不会使用它。
5、modules也是辅助方法。比如modulesA有一个完整的state、actions、getters、mutations;modulesB也可以有一个完整的state、actions、getters、mutations,他就是将store分割成模块,避免混淆。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:


浏览器与NodeJS的EventLoop异同以及部分机制

利用javascript判断浏览器类型  

The above is the detailed content of Vue's parent-child components, parent-child component value transfer and a brief analysis of vuex. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

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 the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

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 vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

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 vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

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.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor