Home > Web Front-end > Vue.js > body text

How to set up parent-child communication in vuejs

青灯夜游
Release: 2023-01-13 00:45:26
Original
2079 people have browsed it

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>{{ 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
  }
})
Copy after login

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;
    }
  }
})
Copy after login

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
    v-bind:title="doc.title"
    v-on:update:title="doc.title = $event">
</text-document>
Copy after login

So we can use .sync syntax sugar to be abbreviated into the following form

<text-document v-bind:title.sync="doc.title"></text-document>
Copy after login

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
  }
})
Copy after login

There is only one sentence in the code:

this.$emit(&#39;update:name&#39;, newVal)
Copy after login

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>
Copy after login
let Child = Vue.extend({
  template: &#39;<h2>{{ 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;)
    }
  }
})
Copy after login

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 id="app">

  <son></son>

</div>

let Son = Vue.extend({
  template: &#39;<h2>son</h2>&#39;,
  inject: {
    house: {
      default: &#39;没房&#39;
    },
    car: {
      default: &#39;没车&#39;
    },
    money: {
      // 长大工作了虽然有点钱
      // 仅供生活费,需要向父母要
      default: &#39;¥4500&#39;
    }
  },
  created () {
    console.log(this.house, this.car, this.money)
    // -> &#39;房子&#39;, &#39;车子&#39;, &#39;¥10000&#39;
  }
})

new Vue({
  el: &#39;#app&#39;,
  provide: {
    house: &#39;房子&#39;,
    car: &#39;车子&#39;,
    money: &#39;¥10000&#39;
  },
  components: {
    Son
  }
})
Copy after login

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!