Home  >  Article  >  Web Front-end  >  How to set up parent-child communication in vuejs

How to set up parent-child communication in vuejs

青灯夜游
青灯夜游Original
2021-09-06 15:26:122115browse

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
  }
})

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

3aad4a5f8d6d21b85f13f5b7d90449ce
d093019edc1fd049b9381d54424ed8e7
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>{{ 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.

ab509c080ec9f7ec77efedb1cdcd4bed

  1207412ca14c1d8bb1c5d564f723d29198f9e0de16d4632c0e387ffd4bb1294d

16b28748ea4df4d9c2150843fecfba68

let Son = Vue.extend({
  template: 'c1a436a314ed609750bd7c7d319db4dason2e9b454fa8428549ca2e64dfac4625cd',
  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