vue父子组件传参和接收的方法

在Vue中,组件之间传递参数常用的方法有以下几种:

父组件向子组件传递参数

父组件向子组件传递参数可以通过props属性实现,父组件将需要传递的参数作为props属性的值传递给子组件,子组件通过props接收该参数。例如:

父组件:

<template>
  <child-component :name="name"></child-component>
</template>

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

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      name: 'Tom'
    }
  }
}
</script>

子组件:

<template>
  <div>姓名:{{ name }}</div>
</template>

<script>
export default {
  props: {
    name: {
      type: String,
      required: true
    }
  }
}
</script>

子组件向父组件传递参数

子组件向父组件传递参数可以通过自定义事件实现,子组件通过$emit方法触发一个自定义事件,传递需要传递的参数,父组件通过在子组件上绑定自定义事件实现接收参数。例如:

父组件:

<template>
  <child-component @age-change="onAgeChange"></child-component>
  <div>年龄:{{ age }}</div>
</template>

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

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      age: 18
    }
  },
  methods: {
    onAgeChange(newAge) {
      this.age = newAge;
    }
  }
}
</script>

子组件:

<template>
  <div>
    <button @click="changeAge">改变年龄</button>
  </div>
</template>

<script>
export default {
  methods: {
    changeAge() {
      this.$emit('age-change', 20);
    }
  }
}
</script>

以上是两种最常用的Vue组件间传递参数的方法,还有其他的传递参数的方式,如路由传参、Vuex传参等。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值