Home Web Front-end Vue.js Programming tips and precautions for Vue component communication

Programming tips and precautions for Vue component communication

Jul 18, 2023 pm 08:02 PM
Precautions Programming skills vue component communication

Programming tips and precautions for Vue component communication

Vue.js is a popular JavaScript framework. Due to its simplicity, ease of use and powerful data binding capabilities, more and more developers choose it. Use Vue to develop front-end applications. In the development process of Vue, component communication is a very important topic. Good component communication can improve development efficiency and code maintainability. This article will introduce some programming skills and precautions for Vue component communication.

1. Parent-child component communication
In Vue, parent-child component communication is the most common way. The parent component passes data to the child component through props, and the child component passes data to the parent component through events.

1. Use props to pass data

Parent components can pass data to child components through props. Child components can receive data passed by parent components and perform rendering or other operations.

// 父组件
<template>
  <div>
    <child-component :message="message" />
  </div>
</template>

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

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      message: 'Hello Vue!'
    }
  }
}
</script>

// 子组件
<template>
  <div>
    <p>{{ message }}</p>
  </div>
</template>

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

In the above code, the parent component passes message to the child component through props, and the child component uses the props option to declare the received properties.

2. Use events to pass data

The child component can trigger a custom event through the $emit method and pass the data to the parent component. The parent component can listen to the events triggered by the child component through v-on and obtain the passed data.

// 子组件
<template>
  <button @click="handleClick">点击我触发事件</button>
</template>

<script>
export default {
  methods: {
    handleClick() {
      this.$emit('my-event', 'Hello Parent!')
    }
  }
}
</script>

// 父组件
<template>
  <div>
    <child-component @my-event="handleEvent" />
  </div>
</template>

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

export default {
  components: {
    ChildComponent
  },
  methods: {
    handleEvent(message) {
      console.log(message)
    }
  }
}
</script>
Copy after login

In the above code, the child component triggers the my-event event through the this.$emit method and sends the data 'Hello Parent!' Passed to the parent component. The parent component uses v-on to listen to the my-event event and calls the corresponding method to handle the event.

2. Non-parent-child component communication
In addition to parent-child component communication, sometimes we also need to communicate between non-parent-child components. Commonly used methods include using a Vue instance as a central event bus or using Vuex for state management.

1. Use a Vue instance as the central event bus

You can create a Vue instance as the central event bus. Subcomponents trigger events through this instance, and other components receive data by listening to events.

// EventBus.js
import Vue from 'vue';
export const EventBus = new Vue();

// 子组件A
<template>
  <button @click="handleClick">点击我触发事件</button>
</template>

<script>
import { EventBus } from './EventBus.js';

export default {
  methods: {
    handleClick() {
      EventBus.$emit('my-event', 'Hello!')
    }
  }
}
</script>

// 子组件B
<template>
  <div>
    <p>{{ message }}</p>
  </div>
</template>

<script>
import { EventBus } from './EventBus.js';

export default {
  data() {
    return {
      message: ''
    }
  },
  mounted() {
    EventBus.$on('my-event', (message) => { 
      this.message = message;
    })
  }
}
</script>
Copy after login

In the above code, we created a Vue instance named EventBus and implemented communication between sub-components through this instance. Subcomponent A triggers the custom event my-event through EventBus.$emit, and subcomponent B listens to my-event# through EventBus.$on ##Events and update data.

2. Use Vuex for state management

Vuex is a state management library officially provided by Vue. You can use Vuex to manage the state of your application and implement communication between components.

// store.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    message: ''
  },
  mutations: {
    setMessage(state, message) {
      state.message = message;
    }
  },
  actions: {
    updateMessage({ commit }, message) {
      commit('setMessage', message);
    }
  },
  getters: {
    getMessage(state) {
      return state.message;
    }
  }
});

// 子组件A
<template>
  <button @click="handleClick">点击我触发事件</button>
</template>

<script>
import { mapActions } from 'vuex';

export default {
  methods: {
    ...mapActions(['updateMessage']),
    handleClick() {
      this.updateMessage('Hello Vuex!');
    }
  }
}
</script>

// 子组件B
<template>
  <div>
    <p>{{ message }}</p>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';

export default {
  computed: {
    ...mapGetters(['getMessage']),
    message() {
      return this.getMessage;
    }
  }
}
</script>
Copy after login
In the above code, we use

Vuex to create a store, including state, mutations, actions and getters. Subcomponent A updates the value of message by calling the updateMessage method through the mapActionsauxiliary function. Subcomponent B obtains the value of message through the mapGetters auxiliary function.

3. Notes

    Make good use of computed properties: In Vue, computed properties are a very useful feature. Using calculated attributes can avoid writing complex expressions in templates, and can also cache the results of multiple data attribute calculations to improve performance.
  1. Try to avoid modifying props directly: In Vue, props are read-only, and the value of props should not be modified directly. If you need to modify the value of props in a subcomponent, you should convert it to the data attribute of the subcomponent and modify it inside the subcomponent. If you need to pass the modified value to the parent component, you can use the emit event.
  2. Use $refs to get sub-component instances: In some scenarios, we want to get the sub-component instance in the parent component, you can use $refs. By adding the ref attribute to the child component, the child component instance can be obtained through this.$refs in the parent component.
Summary

In Vue component communication, parent-child component communication and non-parent-child component communication are the two most common ways. Parent-child component communication can realize data transfer and interaction through props and events. Non-parent-child component communication can be achieved by creating a Vue instance as a central event bus or using Vuex for state management. When writing Vue component communication code, we should make good use of calculated properties, avoid directly modifying props, and use $refs to obtain subcomponent instances and other techniques to improve development efficiency and code maintainability.

The above is the detailed content of Programming tips and precautions for Vue component communication. For more information, please follow other related articles on the PHP Chinese website!

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

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to decompress an iso file How to decompress an iso file Feb 19, 2024 pm 04:07 PM

An ISO file is a common disc image file format that is typically used to store the entire contents of a disc, including files and file systems. When we need to access the contents of the ISO file, we need to decompress it. This article will introduce several common methods to decompress ISO files. Decompression using a virtual optical drive This is one of the most common methods of decompressing ISO files. First, we need to install a virtual optical drive software, such as DAEMON Tools Lite, PowerISO, etc. Then, double-click the virtual optical drive software icon

Introduction to matters needing attention during the Mingchao test Introduction to matters needing attention during the Mingchao test Mar 13, 2024 pm 08:13 PM

During the Mingchao test, please avoid system upgrades, factory resets, and parts replacement to prevent information loss and abnormal game login. Special reminder: There is no appeal channel during the testing period, so please handle it with caution. Introduction to matters needing attention during the Mingchao test: Do not upgrade the system, restore factory settings, replace equipment components, etc. Notes: 1. Please upgrade the system carefully during the test period to avoid information loss. 2. If the system is updated, it may cause the problem of being unable to log in to the game. 3. At this stage, the appeal channel has not yet been opened. Players are advised to choose whether to upgrade at their own discretion. 4. At the same time, one game account can only be used with one Android device and one PC. 5. It is recommended that you wait until the test is completed before upgrading the mobile phone system or restoring factory settings or replacing the device.

C++ Development Notes: Avoid Null Pointer Exceptions in C++ Code C++ Development Notes: Avoid Null Pointer Exceptions in C++ Code Nov 22, 2023 pm 02:38 PM

In C++ development, null pointer exception is a common error, which often occurs when the pointer is not initialized or is continued to be used after being released. Null pointer exceptions not only cause program crashes, but may also cause security vulnerabilities, so special attention is required. This article will explain how to avoid null pointer exceptions in C++ code. Initializing pointer variables Pointers in C++ must be initialized before use. If not initialized, the pointer will point to a random memory address, which may cause a Null Pointer Exception. To initialize a pointer, point it to an

How to start a live broadcast on Douyin for the first time? What should you pay attention to when broadcasting live for the first time? How to start a live broadcast on Douyin for the first time? What should you pay attention to when broadcasting live for the first time? Mar 22, 2024 pm 04:10 PM

With the rise of short video platforms, Douyin has become an indispensable part of many people's daily lives. Live broadcasting on Douyin and interacting with fans are the dreams of many users. So, how do you start a live broadcast on Douyin for the first time? 1. How to start a live broadcast on Douyin for the first time? 1. Preparation To start live broadcast, you first need to ensure that your Douyin account has completed real-name authentication. You can find the real-name authentication tutorial in &quot;Me&quot; -&gt; &quot;Settings&quot; -&gt; &quot;Account and Security&quot; in the Douyin APP. After completing the real-name authentication, you can meet the live broadcast conditions and start live broadcast on the Douyin platform. 2. Apply for live broadcast permission. After meeting the live broadcast conditions, you need to apply for live broadcast permission. Open Douyin APP, click &quot;Me&quot;-&gt;&quot;Creator Center&quot;-&gt;&quot;Direct

Steps and precautions for using localstorage to store data Steps and precautions for using localstorage to store data Jan 11, 2024 pm 04:51 PM

Steps and precautions for using localStorage to store data This article mainly introduces how to use localStorage to store data and provides relevant code examples. LocalStorage is a way of storing data in the browser that keeps the data local to the user's computer without going through a server. The following are the steps and things to pay attention to when using localStorage to store data. Step 1: Check whether the browser supports LocalStorage

Go programming skills: Flexibly delete elements in slices Go programming skills: Flexibly delete elements in slices Apr 02, 2024 pm 05:54 PM

Deleting Go slice elements To delete a single element: use the append() method to create a new slice, excluding the elements you want to delete. Use the copy() method to move elements and adjust their length. Remove multiple elements: Use a for loop to iterate over the slice and exclude the elements you want to remove from the new slice. Use the reverse() method to sort the elements to be deleted, and delete them from back to front to avoid index problems. Choose the most appropriate technique based on the number of elements you want to remove and your performance requirements.

Steps and precautions for installing pip without network Steps and precautions for installing pip without network Jan 18, 2024 am 10:02 AM

Methods and precautions for installing pip in an offline environment. Installing pip becomes a challenge in an offline environment where the network is not smooth. In this article, we will introduce several methods of installing pip in an offline environment and provide specific code examples. Method 1: Use the offline installation package. In an environment that can connect to the Internet, use the following command to download the pip installation package from the official source: pipdownloadpip This command will automatically download pip and its dependent packages from the official source and save it in the current directory. Move the downloaded compressed package to a remote location

Python Development Notes: Avoid Common Memory Leak Problems Python Development Notes: Avoid Common Memory Leak Problems Nov 22, 2023 pm 01:43 PM

As a high-level programming language, Python is becoming more and more popular among developers due to its advantages of being easy to learn, easy to use, and highly efficient in development. However, due to the way its garbage collection mechanism is implemented, Python is prone to memory leaks when dealing with large amounts of memory. This article will introduce the things you need to pay attention to during Python development from three aspects: common memory leak problems, causes of problems, and methods to avoid memory leaks. 1. Common memory leak problems: Memory leaks refer to the inability to release the memory space allocated by the program during operation.

See all articles