Table of Contents
1. Parent component passes data to child component" >1. Parent component passes data to child component
2. The child component passes data to the parent component" >2. The child component passes data to the parent component
3. Data transfer between components at the same level" >3. Data transfer between components at the same level
Home Web Front-end JS Tutorial How to use vue components for data transfer

How to use vue components for data transfer

May 29, 2018 pm 05:52 PM
data components conduct

This time I will show you how to use vue components for data transfer, and what are the precautions for using vue components for data transfer. The following is a practical case, let's take a look.

Vue's component scopes are all isolated and do not allow direct

references to the data of the parent component in the template of the child component. Specific methods must be used to transfer data between components. There are roughly three situations in which data is passed between components:

The parent component passes data to the child component, and the data is passed through props.

The child component passes data to the parent component and passes the data through events.

Transfer data between two sibling components through event bus.

1. Parent component passes data to child component

Child component part:

<template>
  <p class="child">
    {{ msg }}
  </p>
</template>
<script>
export default {
 name: 'child',
 data(){
  return {
  
  }
 },
 props: ['msg']
</script>
Copy after login
In child. In vue, msg is a variable defined in data. Use props: ['msg'] to get the value of msg from the parent component

Parent component part:

<template>
  <p class="child">
    child
    <child :msg="message"></child>
  </p>
</template>
<script>
import child from './child.vue'
export default {
 name: 'parent',
 components: { child },
 data () {
  return {
   message: 'hello vue'
  }
 }
}
</script>
Copy after login
When calling the component, Use v-bind to bind the value of msg to the variable message defined in parent.vue, so that the value of message in parent.vue can be passed to child.vue.

Single data flow

When the message of the parent component changes, the child component will automatically update the

view. But in child components, we don't want to modify props. If you must modify these data, you can use the following method:

Method 1: Assign prop to a local variable, and then modify the local variable if you need to modify it, without affecting prop

export default {
  data(){
    return {
      newMessage: null
    } 
  },
  props: ['message'],
  created(){
    this.newMessage = this.message;
  }
}
Copy after login
Method 2: Process the prop in the calculation of

properties

export default {
  props: ['message'],
  computed: {
    newMessage(){
      return this.message + ' 哈哈哈';
    }
  }
}
Copy after login

2. The child component passes data to the parent component

The subcomponent mainly passes data to the parent component through practice.

The subcomponent part:

<template>
  <p class="child">
   <span>用户名:</span>
   <input v-model="username" @change="sendUser" />
  </p>
</template>
Copy after login
In the html of the subcomponent, when the value in the input changes, the username is passed to parent.vue.

First declare a sendUser method and use change

event to call sendUser.

<script>
 export default {
  name: 'parend',
  data () {
   return {
     username: ''
   }
  },
  methods: {
   sendUser () {
    this.$emit('changeName', this.username)
   }
  }
}
</script>
Copy after login
In sendUser, use $emit to traverse the changeName event and return this.name, where changeName is a custom event, which functions like a relay. This.name will be passed to the parent through this event components.

Parent component part:

<template>
  <p class="parent">
    <child @changeName="getUser"></child>
    <p>用户名:{{user}}</p>
  </p>
</template>
Copy after login
Declare a getUser method in the parent component, use the changeName event to call the getUser method, and obtain the parameter username passed from the child component

<script>
import child from './child.vue'
export default {
 name: 'parent',
 components: { child },
 data () {
  return {
   user: ''
  }
 },
 methods: {
  getUser(data) {
   this.user = data
  }
 }
}
</script>
Copy after login
The parameter msg in the getUser method is the parameter uesrname passed from the subcomponent.

3. Data transfer between components at the same level

Sometimes two components also need to communicate (non-parent-child relationship). Of course Vue2.0 provides Vuex, but in simple scenarios, an empty Vue instance can be used as the central event bus.

<template>
  <p id="app">
    <c1></c1>  //组件1
    <c2></c2> //组件2
  </p>
</template>
Copy after login
In component c1:

<template>
  <p class="c1">
    page
    <button @click="changeMsg">click</button>
  </p>
</template>
<script>
var Bus = new Vue(); //为了方便将Bus(空vue)定义在一个组件中,在实际的运用中一般会新建一Bus.js
export default {
 name: 'c1',
 data () {
  return {
   message: 'hi'
  }
 },
 methods: {
  changeMsg () {  //点击按钮,将this.message传递给c2
   bus.$emit('sendMsg', this.message)
  }
 }
}
</script>
Copy after login
In component c2:

<template>
  <p class="c2">
    {{msg}}
  </p>
</template>
<script>
var Bus = new Vue();
export default {
 name: 'c2',
 data () {
  return {
   msg: ''
  }
 },
 created () {
  bus.$on('sendMsg',(data)=>{  //data即为c1组件中的message
   this.msg = data
  })
 }
}
</script>
Copy after login
In actual application, the bus is generally extracted:

//Bus.js
import Vue from 'vue'
const Bus = new Vue()
expore default Bus
Copy after login
Component call When referenced (import Bus from './Bus.js')

However, in this way of introduction, the local scope of the Bus may appear after being packaged by webpack, that is, two different Buses are referenced. Resulting in normal communication

Practical application:

Inject Bus into the Vue root object

import Vue from 'vue'
const Bus = new Vue()
var app= new Vue({
  el:'#app',
   data:{
    Bus
  }  
})
Copy after login
Pass

this.$root.Bus.$on() in the subcomponent , this.$root.Bus.$emit() to call

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to use WebPack to configure vue multi-page

How to use the Node.js sandbox environment

The above is the detailed content of How to use vue components for data transfer. 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 Article Tags

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)

Use ddrescue to recover data on Linux Use ddrescue to recover data on Linux Mar 20, 2024 pm 01:37 PM

Use ddrescue to recover data on Linux

Open source! Beyond ZoeDepth! DepthFM: Fast and accurate monocular depth estimation! Open source! Beyond ZoeDepth! DepthFM: Fast and accurate monocular depth estimation! Apr 03, 2024 pm 12:04 PM

Open source! Beyond ZoeDepth! DepthFM: Fast and accurate monocular depth estimation!

How to use Excel filter function with multiple conditions How to use Excel filter function with multiple conditions Feb 26, 2024 am 10:19 AM

How to use Excel filter function with multiple conditions

Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training Apr 01, 2024 pm 07:46 PM

Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training

The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks Apr 29, 2024 pm 06:55 PM

The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks

Slow Cellular Data Internet Speeds on iPhone: Fixes Slow Cellular Data Internet Speeds on iPhone: Fixes May 03, 2024 pm 09:01 PM

Slow Cellular Data Internet Speeds on iPhone: Fixes

The first robot to autonomously complete human tasks appears, with five fingers that are flexible and fast, and large models support virtual space training The first robot to autonomously complete human tasks appears, with five fingers that are flexible and fast, and large models support virtual space training Mar 11, 2024 pm 12:10 PM

The first robot to autonomously complete human tasks appears, with five fingers that are flexible and fast, and large models support virtual space training

The U.S. Air Force showcases its first AI fighter jet with high profile! The minister personally conducted the test drive without interfering during the whole process, and 100,000 lines of code were tested for 21 times. The U.S. Air Force showcases its first AI fighter jet with high profile! The minister personally conducted the test drive without interfering during the whole process, and 100,000 lines of code were tested for 21 times. May 07, 2024 pm 05:00 PM

The U.S. Air Force showcases its first AI fighter jet with high profile! The minister personally conducted the test drive without interfering during the whole process, and 100,000 lines of code were tested for 21 times.

See all articles