Home > Web Front-end > Vue.js > Six ways to communicate between Vue components

Six ways to communicate between Vue components

PHPz
Release: 2023-06-11 20:42:15
Original
6604 people have browsed it

Vue is a popular JavaScript framework for building single-page applications. In Vue, components are the basic unit for building applications. Components are reusable blocks of code used to display and process data. Component communication is one of the core mechanisms for data transfer and interaction between components. In this article, we'll explore six ways in which components communicate.

1. Props and Events

Props and Events are the most basic component communication methods in Vue. Through props, parent components pass data to child components. The child component sends data to the parent component through the events constructor. This communication method is characterized by one-way transmission.

The parent component passes data to the child component through props:

<template>
  <child-component :message="parentMessage"></child-component>
</template>
<script>
  import ChildComponent from './ChildComponent.vue'
  export default {
    data() {
      return {
        parentMessage: 'this is parent'
      }
    },
    components: {
      ChildComponent
    }
  }
</script>
Copy after login

In the child component, you need to declare props and use props to receive data from the parent component:

<template>
  <div>{{ message }}</div>
</template>
<script>
  export default {
    props: ['message']
  }
</script>
Copy after login

Then, the child component sends data to the parent component through events:

<template>
  <button @click="updateParentMessage">Update Parent Message</button>
</template>
<script>
  export default {
    methods: {
      updateParentMessage() {
        this.$emit('update-message', 'this is child');
      }
    }
  }
</script>
Copy after login

In the parent component, you need to listen to events for the child component and receive data from the child component in the event listening function:

<template>
  <child-component :message="parentMessage" @update-message="updateMessage"></child-component>
</template>
<script>
  import ChildComponent from './ChildComponent.vue'
  export default {
    data() {
      return {
        parentMessage: 'this is parent'
      }
    },
    components: {
      ChildComponent
    },
    methods: {
      updateMessage(message) {
        this.parentMessage = message;
      }
    }
  }
</script>
Copy after login

2. Vuex

Vuex is an official plug-in for state management in Vue. Vuex implements a global state management model. It centrally manages the state of all components of the application through a store. When multiple components share state, using Vuex makes it easier to manage data exchange and communication between components.

First, we need to create a Vuex store:

import Vuex from 'vuex'
import Vue from 'vue'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    message: 'hello world'
  },
  mutations: {
    updateMessage(state, message) {
      state.message = message
    }
  },
  actions: {
    updateMessage({ commit }, message) {
      commit('updateMessage', message)
    }
  },
  getters: {
    getMessage: state => state.message
  }
})

export default store
Copy after login

In the component, we can use $store to access the state in the store, and use the commit method to submit mutations to modify the state:

<template>
  <div>{{ this.$store.getters.getMessage }}</div>
  <button @click="updateMessage">Update Message</button>
</template>
<script>
  export default {
    methods: {
      updateMessage() {
        this.$store.dispatch('updateMessage', 'hello vuex')
      }
    }
  }
</script>
Copy after login

3. $parent and $children

Every component in Vue has $parent and $children properties. The $parent property points to the component's parent component, and the $children property points to the component's child components. Through the $parent and $children properties, components can directly access the data and methods of parent and child components.

For example, the parent component can access the data and methods of the child component through the $children attribute:

<template>
  <div>
    {{ $children[0].message }}
    <button @click="$children[0].updateMessage">Update message</button>
  </div>
</template>
Copy after login

In the child component, the message and updateMessage methods need to be defined:

<template>
  <div>{{ message }}</div>
</template>
<script>
  export default {
    data() {
      return {
        message: 'hello child'
      }
    },
    methods: {
      updateMessage() {
        this.message = 'hello parent'
      }
    }
  }
</script>
Copy after login
Copy after login

four , $refs

Every component in Vue has a $refs attribute. The $refs attribute is an object that contains references to subcomponents or DOM elements named using the ref attribute in the component. Through the $refs attribute, components can reference and call each other.

For example, we can obtain the reference of the subcomponent through the ref attribute in the parent component:

<template>
  <div>
    <child-component ref="childComponent"></child-component>
    <button @click="updateMessage">Update message</button>
  </div>
</template>
<script>
  import ChildComponent from './ChildComponent.vue'
  export default {
    components: {
      ChildComponent
    },
    methods: {
      updateMessage() {
        this.$refs.childComponent.updateMessage()
      }
    }
  }
</script>
Copy after login

In the subcomponent, we need to define the updateMessage method:

<template>
  <div>{{ message }}</div>
</template>
<script>
  export default {
    data() {
      return {
        message: 'hello child'
      }
    },
    methods: {
      updateMessage() {
        this.message = 'hello parent'
      }
    }
  }
</script>
Copy after login
Copy after login

5. Event Bus

Event Bus is a widely used central event system that can efficiently deliver events between Vue components. Event Bus is a simple Vue instance that can send events to other Vue components through the $emit method, and can also receive events sent by other Vue components through the $on method.

When implementing Event Bus, we need to create a new Vue instance:

import Vue from 'vue'

const bus = new Vue()

export default bus
Copy after login

Then, we can introduce Event Bus in the component and use $emit to send events and $on to receive events. :

// 发送事件
import Bus from './Bus.js'

Bus.$emit('event-name', data)

// 接收事件
import Bus from './Bus.js'

Bus.$on('event-name', (data) => {
  console.log(data)
})
Copy after login

6. Provide and Inject

The new Provide and Inject in Vue 2.2 are an advanced component communication method. Provide and Inject allow a parent component to pass data to all descendant components, rather than just to direct children. Provide and Inject are a form of component communication that is different from props, events, and $parent/$children. It is a more flexible and encapsulated communication method.

The parent component provides data through provide:

<template>
  <child-component></child-component>
</template>
<script>
  export default {
    provide: {
      message: 'hello provide'
    }
  }
</script>
Copy after login

In the child component, we need to define inject to receive the data passed by the parent component:

<template>
  <div>{{ message }}</div>
</template>
<script>
  export default {
    inject: ['message']
  }
</script>
Copy after login

These are the six types of Vue component communication Introduction to the method. Different application scenarios require different component communication methods. Mastering these communication methods can make the development of Vue components more efficient, simple and flexible.

The above is the detailed content of Six ways to communicate between Vue components. For more information, please follow other related articles on the PHP Chinese website!

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