Home Web Front-end JS Tutorial Vue's parent-child components, parent-child component value transfer and a brief analysis of vuex

Vue's parent-child components, parent-child component value transfer and a brief analysis of vuex

Jul 07, 2018 pm 05:33 PM
javascript vue.js

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 class="test-btn" @click="add">+</button>
    <button class="test-btn" @click="minu">-</button>
    <p class="text-link">这里是son的num:{{num}}</p>
  </p>
</template>
<script>
export default {
  //props:["num"],//接收父组件传递过来的值,这里我先写上
  data () {
    return {
        num:0
    }
  },
   methods:{
       add(){//es6的语法相当于add:function(){}
           this.num++;
       },
       minu(){
           this.num--;
       }
   }
}
</script>
Copy after login

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 v-bind:num="num"></son>//传递一个值给son.vue,这时候可以把son.vue的props那个注释注销掉了
    <p class="text-link">这里是index的num:{{num}}</p>
  </p>
</template>
<script>
import son from './../components/son' 
export default {
  data () {
    return {
      num:10
    }
  },
  components:{
       son
     }
}
</script>
Copy after login

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 v-bind:num="num" v-on:add="icr" v-on:minu="der"></son>//v-on:add="icr"就是绑定一个自定义事件
Copy after login

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

Then the methods in son.vue become

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

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 class="test-btn" @click="add">+</button>
    <button class="test-btn" @click="minu">-</button>
    <p class="text-link">这里是{{num}}</p>
</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 v-bind:num="num" v-on:add="icr" v-on:minu="der"></son>
    <p class="text-link">父{{num}}</p>
</p>
</template>
<script>
import son from './../components/son'
export default {
  data () {
    return {
      num:10
    }
  },
  components:{
       son
   },
   methods:{
       icr(){
           this.num++;
       },
       der(){
           this.num--;
       }
   }
}
</script>
Copy after login

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

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

二、说说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 of this Website
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

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

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles