search
HomeWeb Front-endJS TutorialVue.js component communication example sharing

Vue.js component communication example sharing

Jan 04, 2018 am 10:17 AM
javascriptvue.jsshare

Because I am very interested in Vue.js, and the technology stack I usually work on is also Vue.js, I spent some time studying the Vue.js source code in the past few months, and made a summary and output. Components are one of the most powerful features of Vue.js. Components can extend HTML elements, encapsulating reusable code. This article will share with you several postures for Vue.js component communication. Friends who are interested should take a look.

Written in front

There may be deviations in understanding. Welcome to raise issues and point out, learn together and make progress together.

What is a Vue component?

Component is one of the most powerful features of Vue.js. Components can extend HTML elements, encapsulating reusable code. At a high level, a component is a custom element to which Vue.js's compiler adds special functionality. In some cases, components can also take the form of native HTML elements, extended with the is attribute.

Communication between Vue components

Communication from parent component to child component

Method 1: props

Using props, the parent component can use props to pass to the child component data.

Parent component vue template father.vue

<template>
  <child></child>
</template>
<script>
import child from &#39;./child.vue&#39;;
export default {
  components: {
    child
  },
  data () {
    return {
      message: &#39;father message&#39;;
    }
  }
}
</script>

Child component vue template child.vue

<template>
  <p>{{msg}}</p>
</template>
<script>
export default {
  props: {
    msg: {
      type: String,
      required: true
    }
  }
}
</script>

Method 2 uses $children

Use $children You can Access child components from parent components.

The child component communicates with the parent component

Method 1: Using vue events

The parent component passes the event method to the child component, and the child component triggers the event through $emit and calls back to the parent components.

Parent component vue template father.vue

<template>
  <child></child>
</template>
<script>
import child from &#39;./child.vue&#39;;
export default {
  components: {
    child
  },
  methods: {
    func (msg) {
      console.log(msg);
    }
  }
}
</script>

Child component vue template child.vue

<template>
  <button>点我</button>
</template>
<script>
export default {
  props: {
    msg: {
      type: String,
      required: true
    }
  },
  methods () {
    handleClick () {
      //........
      this.$emit(&#39;msgFunc&#39;);
    }
  }
}
</script>

Method 2: Modify the parent component data by modifying the props passed by the parent component

This method can only be used when the parent component passes a reference variable. Literal variables cannot achieve the corresponding effect. Because the drinking variable ultimately points to the same memory address, whether it is the data in the parent component or the data in the props obtained by the child component, so modifying the data in the props in the child component modifies the data in the parent component.

But this is not recommended. It is not recommended to directly modify the value of props. If the data is used to display modifications, in actual development I often put it into data and pass it back when needed. The parent component then uses events to return data. This keeps the components independent and decoupled, and does not cause abnormal data flow confusion due to the use of the same data. Data is only transmitted through specific interfaces to modify the data, and the internal data status is managed by specialized data.

Method 3: Use $parent

Use $parent to access the data of the parent component.

Data transfer between non-parent-child components and sibling components

For non-parent-child component communication, Vue officially recommends using a Vue instance as the central event bus.

Vue has an internal event mechanism, you can refer to the source code.

$on method is used to listen to an event.

$emit is used to trigger an event.

/*新建一个Vue实例作为中央事件总嫌*/
let event = new Vue();
/*监听事件*/
event.$on('eventName', (val) => {
  //......do something
});
/*触发事件*/
event.$emit('eventName', 'this is a message.');

Multi-level parent-child component communication:

In Vue1.0, two methods, $broadcast and $dispatch, are implemented to broadcast (or dispatch) to child components (or parent components). When the child component (or parent component) listens to the event and returns true, the event will continue to be broadcast (or dispatched) to the grandchild-level component. But this method has been removed in Vue2.0.

When I was learning about element, the open source component library of Ele.me, I found that they re-implemented the broadcast and dispatch methods and introduced them in the form of mixin. For details, please refer to "Talk about element component library broadcast and dispatch". But it is slightly different from the two method implementations of Vue1.0. These two methods implement the functions of event broadcasting to descendant components and event dispatching to multi-level parent components. But it is not an event broadcast in a broad sense. It needs to specify a commentName to broadcast (dispatch) events to the component with the specified component name.

In fact, the internal implementation of these two methods still uses $parent and $children, which are used to traverse child nodes or query parent nodes step by step. When the specified component name is accessed, $emit is called to trigger Specify event.

Complex single-page application data management

When the application is complex enough, please use vuex for data management.

Related recommendations:

Vue sibling component communication method

Detailed explanation of event bus non-parent-child component communication in vue

Deep dive into Vue.js components and component communication

The above is the detailed content of Vue.js component communication example sharing. 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
Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function