vue3-setup语法糖 父子组件传值

父传子接:

父组件传值

<template>

  <div>

    <div>

      我是父亲

      <input type="text" v-model="a" />

    </div>

    <hr />

    <child :info="parent" />

  </div>

</template>

<script setup>

import child from "./child.vue";

import { ref } from "vue";

const a = ref("");

const parent = ref(a);

</script>

<style scoped>

</style>

子组件接收

<template>

  <div>我是孩子 : {{ info }}</div>

</template>

<script setup>

import { toRefs, defineProps } from "vue";

const props = defineProps({

  //子组件接收父组件传递过来的值

  info: String,

});

//使用父组件传递过来的值

const { info } = toRefs(props);

</script>

<style scoped>

</style>

 

 子传父接:

子组件传值:        setup语法糖的是defineEmits

<template>

  <div>我是子组件<input type="text" v-model="a" /></div>

</template>

<script setup>

import { defineEmits, ref } from "vue";

let a = ref("");

let param = {

  content: a,

};

// 使用defineEmits创建名称,接受一个数组

const emit = defineEmits(["params"]);

//传递给父组件

emit("params", param);

</script>

<style>

</style>

父组件接收: 

 

<template>

  <div class="hello">

    我是父组件

    <p>子组件传递的值是 {{ result }}</p>

    <hr />

    <!-- clickChild是子组件绑定的事件,click是父组件接受方式 -->

    <child @params="clickEven" />

  </div>

</template>

<script setup>

import child from "./child.vue";

import { ref } from "vue";

const result = ref("");

const clickEven = (val) => {

  result.value = val.content;

};

</script>

<style scoped>

</style>

Vue 3中,你可以使用`setup`函数来实现父子组件之间的传值。`setup`函数是在组件创建之前执行的,它接收两个参数:`props`和`context`。 要在父组件中向子组件传递值,首先需要在父组件中将值作为属性传递给子组件。然后,在子组件的`setup`函数中可以通过`props`参数访问到父组件传递过来的值。 以下是一个简单的示例: ```vue <template> <div> <p>父组件传递的值: {{ message }}</p> <ChildComponent :message="message" /> </div> </template> <script> import { ref } from 'vue'; import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, setup() { const message = ref('Hello from parent'); return { message }; } }; </script> ``` 在上面的示例中,父组件通过`:message="message"`将`message`作为属性传递给子组件。在子组件的`setup`函数中,通过`props`参数可以访问到父组件传递过来的值。 ```vue <template> <div> <p>子组件接收到的值: {{ message }}</p> </div> </template> <script> export default { props: { message: { type: String, required: true } }, setup(props) { // 可以通过 props.message 访问到父组件传递过来的值 return { message: props.message }; } }; </script> ``` 在子组件中,可以通过`props`对象访问到父组件传递过来的值,并将其赋值给一个本地变量,以便在模板中使用。 这样就实现了父子组件之间的传值。注意,`setup`函数中返回的是一个对象,该对象中的属性可以在模板中直接使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值