vue父子组件间互相传递数据

vue父子组件间传递参数

1.父传子
使用 props 向子组件传递数据。
在父组件中定义 hMsg参数,v:bind 绑定childMsg的值为hMsg;
子组件使用props获取父组件传递过来的数据

parent.vue

<template>
  <div>
    <h2>parent</h2>
    <Child1 :child1Msg="hMsg"></Child1>
  </div>
</template>

<script>
import Child1 from './child1'
export default {
  name: 'parent',
  data () {
    return {
      hMsg: 'Child1MsgS'
    }
  },
  components: {
    Child1
  }
}
</script>

child1.vue
使用props接收数据值

<template>
    <div>{{child1Msg}}</div>
</template>

<script>
export default {
  name: 'child1',
  props: ['child1Msg']
}
</script>

2.子传父
子组件通过事件将数据传递给父组件
首先,子组件想要将username参数传递给父组件,用change事件来触发setUser函数,
在 setUser 中,使用了 $emit 来遍历 transferUser 事件,并返回 this.username
其中 transferUser 是一个自定义的事件,功能类似于一个中转,this.username 将通过这个事件传递给父组件
child2.vue

<template>
    <div>
      <label>用户名:</label>
      <input v-model="username" @change="setUsername">
    </div>
</template>

<script>
export default {
  name: 'child2',
  data () {
    return {
      username: ''
    }
  },
  methods: {
    setUsername: function () {
      this.$emit('transferUser', this.username)
    }
  }
}
</script>

在父组件 中,声明了一个方法 getUser,用 transferUser 事件调用 getUser 方法,获取到从子组件传递过来的参数 username
getUser方法中的data,就是从子组件中传递过来的数据 username

parent.vue

<template>
  <div>
    <h2>parent</h2>
    <Child2 @transferUser="getUser"></Child2>
    <p>用户名为: {{user}}</p>
  </div>
</template>

<script>
import Child2 from './child2'
export default {
  name: 'parent',
  data () {
    return {
      user: ''
    }
  },
  components: {
    Child2
  },
  methods: {
    getUser: function (data) {
      this.user = data
    }
  }
}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值