vue子组件向父组件传递数据详解

文章演示了在Vue.js中如何进行父子组件之间的数据传递。首先,在父组件(app.vue)中引入并注册子组件(HelloWorld.vue),然后在父组件的模板中渲染子组件。子组件通过$emit触发自定义事件并传递数据,而父组件通过监听这个事件来接收并处理来自子组件的数据。

1、在父组件app.vue的scripts下引入子组件HelloWorld.vue,例如

import HelloWorld from './components/HelloWorld'

2、添加到components中,

components:{
    HelloWorld
  }

3、在父组件的template下渲染子组件的内容,

 <HelloWorld />

4、子组件向父组件传递数据,代码如下,点击按钮后,调用sendMsg方法

<template>
  <button @click="sendMsg">点击传递参数</button>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods: {
    sendMsg(){
    	//第一个参数是自定义的事件名,它携带第二个参数的内容
    	//第二个参数是传递的数据
        this.$emit('receive',this.msg)
    }
  }
}
</script>

5、父组件接收数据,代码如下,在<HelloWorld @receive=“getMsg”/>中调用子组件的自定义事件receive和父组件的getMsg方法,其中getMsg(data)方法中的data是用来接收子组件携带的数据,从而实现了从子组件到父组件数据的传递

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <p >{{message}}</p>
    <HelloWorld @receive="getMsg"/>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld'
export default {
  name: 'App',
  components:{
    HelloWorld
  },
  data(){
    return {
      message:''
    }
  },
  methods:{
    getMsg(data){
      this.message = data
    }
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Double Handsome

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值