Vue父子组件通讯方式及实现

68. Vue父子组件通讯方式及实现

1. props和$emit

父组件通过props向子组件传递数据,子组件通过$emit触发父组件定义的事件来传递数据。

父组件:

<template>
  <div>
    <child-component :message="message" @update-message="updateMessage">child-component>
  div>
template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  name: 'ParentComponent',
  components: {
    ChildComponent
  },
  data() {
    return {
      message: 'Hello World!'
    }
  },
  methods: {
    updateMessage(newMessage) {
      this.message = newMessage;
    }
  }
}
script>

子组件:

<template>
  <div>
    <p>{{ message }}p>
    <button @click="updateMessage">Update Messagebutton>
  div>
template>

<script>
export default {
  name: 'ChildComponent',
  props: ['message'],
  methods: {
    updateMessage() {
      this.$emit('update-message', 'New Message');
    }
  }
}
script>

2. $parent和$children

父组件可以通过$children属性获取到所有子组件的实例,并通过$parent属性获取到自己的父组件实例。

父组件:

<template>
  <div>
    <child-component>child-component>
  div>
template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  name: 'ParentComponent',
  components: {
    ChildComponent
  },
  methods: {
    updateMessage(newMessage) {
      this.message = newMessage;
    }
  }
}
script>

子组件:

<template>
  <div>
    <p>{{ message }}p>
    <button @click="updateMessage">Update Messagebutton>
  div>
template>

<script>
export default {
  name: 'ChildComponent',
  data() {
    return {
      message: 'Hello World!'
    }
  },
  methods: {
    updateMessage() {
      this.$parent.updateMessage('New Message');
    }
  }
}
script>

3. $refs

父组件可以通过ref属性给子组件设置一个引用,然后通过$refs获取到子组件的实例,从而调用子组件的方法或者访问子组件的属性。

父组件:

<template>
  <div>
    <child-component ref="child">child-component>
  div>
template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  name: 'ParentComponent',
  components: {
    ChildComponent
  },
  methods: {
    updateMessage() {
      this.$refs.child.updateMessage('New Message');
    }
  }
}
script>

子组件:

<template>
  <div>
    <p>{{ message }}p>
    <button @click="updateMessage">Update Messagebutton>
  div>
template>

<script>
export default {
  name: 'ChildComponent',
  data() {
    return {
      message: 'Hello World!'
    }
  },
  methods: {
    updateMessage(newMessage) {
      this.message = newMessage;
    }
  }
}
script>

你可能感兴趣的:(dairy,vue,vue.js,javascript,ecmascript,组件通讯,父子组件)