How to set up parent-child communication in vuejs
How to set up parent-child communication in vuejs: 1. The parent component uses props to pass data to the child component; 2. The child component sends messages to the parent component through "$emit"; 3. Use ".sync" syntactic sugar; 4. Use "$attrs" and "$listeners"; 5. Use private and inject.
The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.
Vue has the following communication methods between parent and child components:
props
- ## $emit -- commonly used for component encapsulation
- .sync -- syntactic sugar
- $attrs and $listeners -- used for component encapsulation There are many
- privide and inject -- high-order components
1, props
This is commonly used in daily development. To put it simply, we can pass data to child components through props. Just like a water pipe, the data of the parent component flows from top to bottom to the child component. , cannot flow against the flow. This is also the single data flow of Vue's design introduction.<div id="app"> <child :content="message"></child> </div> // Js let Child = Vue.extend({ template: '<h2 id="nbsp-content-nbsp">{{ content }}</h2>', props: { content: { type: String, default: () => { return 'from child' } } } }) new Vue({ el: '#app', data: { message: 'from parent' }, components: { Child } })
2. $emit
The official introduction is to trigger events on the current instance, and additional parameters will be passed to the listener callback.<div id="app"> <my-button @greet="sayHi"></my-button> </div> let MyButton = Vue.extend({ template: '<button @click="triggerClick">click</button>', data () { return { greeting: 'vue.js!' } }, methods: { triggerClick () { this.$emit('greet', this.greeting) } } }) new Vue({ el: '#app', components: { MyButton }, methods: { sayHi (val) { alert('Hi, ' + val) // 'Hi, vue.js!' } } })
3. .sync modifier
used to exist as a two-way binding function in vue1.x, that is, the child component can modify the value in the parent component . Because it violated the design concept of one-way data flow, it was removed in vue2.x, but this .sync modifier was reintroduced in vue 2.3.0 and above. But it only exists as a compile-time syntactic sugar. It is extended as a v-on listener that automatically updates the parent component's properties. In some cases, we may need to perform "two-way binding" on a prop. Unfortunately, true two-way binding creates maintenance problems because child components can modify their parent components with no obvious source of change in either parent or child components. The syntax sugar is written in the following form<text-document> </text-document>So we can use .sync syntax sugar to be abbreviated into the following form
<text-document v-bind:title.sync="doc.title"></text-document>So how to achieve two-way binding, such as changing the sub- The value in the component text box also changes the value in the parent component. The code is as follows
<div id="app"> <login :name.sync="userName"></login> {{ userName }} </div> let Login = Vue.extend({ template: ` <div class="input-group"> <label>姓名:</label> <input v-model="text"> </div> `, props: ['name'], data () { return { text: '' } }, watch: { text (newVal) { this.$emit('update:name', newVal) } } }) new Vue({ el: '#app', data: { userName: '' }, components: { Login } })There is only one sentence in the code:
this.$emit('update:name', newVal)The official syntax is: update:myPropName where myPropName represents the prop to be updated. value. Of course, if you don’t use .sync syntax sugar and use .$emit above, you can achieve the same effect
4, $attrs and $listeners
The official website’s support for $attrs The explanation is as follows: Contains property bindings (except class and style) that are not recognized (and obtained) as props in the parent scope. When a component does not declare any props, all parent scope bindings (except class and style) will be included here, and internal components can be passed in via v-bind="$attrs" - when creating high-level components very useful. The official website explains $listeners as follows: Contains v-on event listeners in the parent scope (without .native modifier). It can be passed into internal components via v-on="$listeners" - very useful when creating higher level components. The $attrs and $listeners attributes are like two storage boxes. One is responsible for storing attributes and the other is responsible for storing events. They both save data in the form of objects.<div id="app"> <child :foo="foo" :bar="bar" @one.native="triggerOne" @two="triggerTwo"> </child> </div>
let Child = Vue.extend({ template: '<h2 id="nbsp-foo-nbsp">{{ foo }}</h2>', props: ['foo'], created () { console.log(this.$attrs, this.$listeners) // -> {bar: "parent bar"} // -> {two: fn} // 这里我们访问父组件中的 `triggerTwo` 方法 this.$listeners.two() // -> 'two' } }) new Vue({ el: '#app', data: { foo: 'parent foo', bar: 'parent bar' }, components: { Child }, methods: { triggerOne () { alert('one') }, triggerTwo () { alert('two') } } })As you can see, we can It is very convenient to pass data through $attrs and $listeners and call and process it where needed. Of course, we can also pass it down level by level through v-on="$listeners", and the descendants will be endless!
5, private and inject
Let’s take a look at the official description of provide / inject: Provide and inject are mainly high-end plug-ins/components The library provides use cases. Not recommended for use directly in application code. And this pair of options needs to be used together to allow an ancestor component to inject a dependency into all its descendants, no matter how deep the component hierarchy is, and it will always take effect from the time the upstream and downstream relationships are established.<div> <son></son> </div> let Son = Vue.extend({ template: '<h2 id="son">son</h2>', inject: { house: { default: '没房' }, car: { default: '没车' }, money: { // 长大工作了虽然有点钱 // 仅供生活费,需要向父母要 default: '¥4500' } }, created () { console.log(this.house, this.car, this.money) // -> '房子', '车子', '¥10000' } }) new Vue({ el: '#app', provide: { house: '房子', car: '车子', money: '¥10000' }, components: { Son } })For more examples, you can refer to the element-ui source code, which uses a large number of this methodRelated recommendations: "
vue.js Tutorial"
The above is the detailed content of How to set up parent-child communication in vuejs. For more information, please follow other related articles on the PHP Chinese website!

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

Vue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.

Vue.js is suitable for small to medium-sized projects, while React is more suitable for large and complex applications. 1. Vue.js' responsive system automatically updates the DOM through dependency tracking, making it easy to manage data changes. 2.React adopts a one-way data flow, and data flows from the parent component to the child component, providing a clear data flow and an easy-to-debug structure.

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

The methods to implement the jump of a tag in Vue include: using the a tag in the HTML template to specify the href attribute. Use the router-link component of Vue routing. Use this.$router.push() method in JavaScript. Parameters can be passed through the query parameter and routes are configured in the router options for dynamic jumps.

There are the following methods to implement component jump in Vue: use router-link and <router-view> components to perform hyperlink jump, and specify the :to attribute as the target path. Use the <router-view> component directly to display the currently routed rendered components. Use the router.push() and router.replace() methods for programmatic navigation. The former saves history and the latter replaces the current route without leaving records.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Linux new version
SublimeText3 Linux latest version

Atom editor mac version download
The most popular open source editor

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.

SublimeText3 Mac version
God-level code editing software (SublimeText3)