search
HomeWeb Front-endVue.jsHow to set up parent-child communication in vuejs

How to set up parent-child communication in vuejs

Sep 06, 2021 pm 03:26 PM
vuejsfather-son communication

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.

How to set up parent-child communication in vuejs

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

The following will introduce respectively

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: &#39;<h2 id="nbsp-content-nbsp">{{ content }}</h2>&#39;,
  props: {
    content: {
      type: String,
      default: () => { return &#39;from child&#39; }
    }
  }
})
new Vue({
  el: &#39;#app&#39;,
  data: {
    message: &#39;from parent&#39;
  },
  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: &#39;<button @click="triggerClick">click</button>&#39;,
  data () {
    return {
      greeting: &#39;vue.js!&#39;
    }
  },
  methods: {
    triggerClick () {
      this.$emit(&#39;greet&#39;, this.greeting)
    }
  }
})
new Vue({
  el: &#39;#app&#39;,
  components: {
    MyButton
  },
  methods: {
    sayHi (val) {
      alert(&#39;Hi, &#39; + val) // &#39;Hi, vue.js!&#39;
    }
  }
})

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: [&#39;name&#39;],
  data () {
    return {
      text: &#39;&#39;
    }
  },
  watch: {
    text (newVal) {
      this.$emit(&#39;update:name&#39;, newVal)
    }
  }
})

new Vue({
  el: &#39;#app&#39;,
  data: {
    userName: &#39;&#39;
  },
  components: {
    Login
  }
})

There is only one sentence in the code:

this.$emit(&#39;update:name&#39;, 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: &#39;<h2 id="nbsp-foo-nbsp">{{ foo }}</h2>&#39;,
  props: [&#39;foo&#39;],
  created () {
    console.log(this.$attrs, this.$listeners)
    // -> {bar: "parent bar"}
    // -> {two: fn}
    // 这里我们访问父组件中的 `triggerTwo` 方法
    this.$listeners.two()
    // -> &#39;two&#39;
  }
})

new Vue({
  el: &#39;#app&#39;,
  data: {
    foo: &#39;parent foo&#39;,
    bar: &#39;parent bar&#39;
  },
  components: {
    Child
  },
  methods: {
    triggerOne () {
      alert(&#39;one&#39;)
    },
    triggerTwo () {
      alert(&#39;two&#39;)
    }
  }
})

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 method

Related 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!

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
React vs. Vue: Which Framework Does Netflix Use?React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AM

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

The Choice of Frameworks: What Drives Netflix's Decisions?The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AM

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.

React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

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 in the Frontend: Real-World Applications and ExamplesVue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AM

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 and React: Understanding the Key DifferencesVue.js and React: Understanding the Key DifferencesApr 10, 2025 am 09:26 AM

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 vs. React: Project-Specific ConsiderationsVue.js vs. React: Project-Specific ConsiderationsApr 09, 2025 am 12:01 AM

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.

How to jump a tag to vueHow to jump a tag to vueApr 08, 2025 am 09:24 AM

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.

How to implement component jump for vueHow to implement component jump for vueApr 08, 2025 am 09:21 AM

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.

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

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 new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

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

SublimeText3 Mac version

God-level code editing software (SublimeText3)