Vue3父组件与子组件的参数传递

一、定义父路由和子路由

1.子组件:

<template>
 这里是子路由
 <div></div>
    <input type="text">

</template>

2.父组件:在vue3中调用子组件只需要利用import导入就可以直接使用,与vue2不同,vue2中需要在父组件对应路由下添加子路由;

<template>
    <div>
  <Child></Child>
    </div>
</template>
<script setup>
import Child from './Child.vue';
</script>

二、传参

1.vue2的方法

vue2的方法仍然还支持,首先在父组件中调用子路由的时候传入参数

<template>
    <div>
  <Child type="password" placeholder="请输入。。。"></Child>
    </div>
</template>
<script setup>
import Child from './Child.vue';
</script>

然后在组见中定义props接收传入参数,需要在接收参数的地方进行v-bind双向绑定

<template>
 这里是子路由
 <div></div>
    <input :type="type" :placeholder="placeholder">

</template>
<script>
export default{
 props:['type','placeholder'],
}

</script>

2.vue3的新增方法

父组件和上边的vue2的传入参数一致

子组件通过defineProps方法进行接收,绑定的方式有两种(1.直接用接受的属性绑定,2.用定义的props下的对应属性进行绑定)(用1.绑定的type,用2.绑定的placeholder)

<template>
 这里是子路由
 <div></div>
    <input :type="type" :placeholder="props.placeholder">

</template>
<script setup>
import { defineProps } from 'vue';
const props=defineProps(['type','placeholder']);

</script>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3中,组件向子组件传递参数的方式主要有以下两种: 1.使用v-bind绑定数值,然后通过props在子组件中接收使用。具体步骤如下:[^1] - 在组件中,使用v-bind将数值绑定到子组件上: ```html <template> <div> <child-component :message="msg"></child-component> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { name: 'ParentComponent', components: { ChildComponent }, data() { return { msg: '组件向子组件传参示例' } } } </script> ``` - 在子组件中,使用props定义接收的属性名称,然后通过template中的插值语法将props中的数值显示出来: ```html <template> <div> <p>{{ message }}</p> </div> </template> <script> import { defineProps } from 'vue'; export default { name: 'ChildComponent', props: { message: { type: String, default: '' } }, setup(props) { return { message: props.message } } } </script> ``` 2.使用defineProps在子组件中定义props属性,然后在组件中通过v-bind绑定数据到子组件的props属性中。具体步骤如下: - 在子组件中,使用defineProps定义props属性接收组件传递的参数: ```html <template> <div> <p>{{ type }}</p> </div> </template> <script> import { defineProps } from 'vue'; export default { name: 'ChildComponent', emits: ['update:type'], props: defineProps({ type: { type: String, default: 'edit' } }), methods: { updateType() { this.$emit('update:type', 'update'); } } } </script> ``` - 在组件中,使用v-bind绑定数值到子组件的props属性中,并在需要更新时使用v-on监听子组件的自定义事件来进行更新。 ```html <template> <div> <child-component :type="type" @update:type="handleUpdate"></child-component> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { name: 'ParentComponent', components: { ChildComponent }, data() { return { type: 'edit' } }, methods: { handleUpdate(data) { this.type = data; } } } </script> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值