欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Vue3-Props 组件数据传递

最编程 2024-04-27 13:40:38
...

Props组件传递(父传子)

一、前言

  1. vue3setup中,我们使用defineProps来定义父组件传递的props

  2. 在setup语法糖中用definePropsdefineProps是编译器宏,无需引入)。

二、defineProps使用

子组件:Child.vue

<template>
  <h1>{{ message }},num={{ num }}</h1>
</template>

<script setup>
const props = defineProps({
  message: {
    type: String,
    require: true,
    default: "默认值"
  },
  num: Number,
});
</script>

父组件:Parent.vue

<template>
  <h1>Parent</h1>
  <Child message="hello" :num="123"/>
</template>

<script setup>
import Child from "./components/Child.vue";
</script>

1.定义后props值可直接在模板中使用或赋值给data对象。

2.传数值类型或者复杂类型时需要加‘:’传递。

2.由defineProps定义出的props对象,是一个proxy对象,所有特性和reactive基本相同,只不过由defineProps定义出的props对象的值是只读的,还有在模板上可以单独属性直接使用。

三、注意事项

  1. defineProps只能在setup中使用,且只能在setup的顶层使用,不能在局部作用域使用。

  2. 和vue2一样的原则,defineProps声明的props的值是只读readonly的,不能修改,也就是说,当传过来的是原始值时不能修改,当是对象类型时,不能修改对象类型的引用地址。

Props组件传递(子传父)

一、前言

在vue3中使用props实现子传父的原理是使用props的function数据类型来实现。

二、案例

Child.vue

<template>
  <h1>{{ title }}</h1>
</template>

<script setup>
import { onMounted } from "vue";

const props = defineProps({
  title: String,
  onEvent: Function, //Function类型
});

onMounted(() => {
  props.onEvent("hello");
});
</script>

Parent.vue

<template>
  <h1>Parent</h1>
  <Child :onEvent="dataFn" />
</template>

<script setup>
import { reactive } from "vue";
import Child from "./components/Child.vue";

const stateData = reactive({})
const dataFn = (data) => {
  stateData.message = data
};
</script>

1.父组件传递dataFn函数给子组件调用,子组件使用onEvent函数实现对dataFn的调用并传参,从而父组件里的函数可以接收到传递的参数,实现了子传父。

推荐阅读