Vue3的父子传参
在vue3中setup接收两个参数,第一个参数是props,即父组件向子组件传递的props值。第二个值为context。
父组件
代码示例:
<template>
<div style="color: aqua">父组件</div>
<div>子组件对我说:{{ children_msg }}</div>
<children :title="msg" @listen="listenToChildren"></children>
{{ value }}
</template>
<script lang="ts">
import children from "@/components/child.vue"
import { defineComponent, ref } from "vue"
export default defineComponent({
components: {
children,
},
name: "father",
setup() {
let msg = "这是父组件"
// ref的作用是实现响应式, 如果没有ref则不能实现响应式(引用数据类型用reactive)
let children_msg = ref("")
let listenToChildren = (val) => {
// 使用ref包裹的数据,需要通过.value的形式访问他的值
children_msg.value = val
}
return {
msg,
children_msg,
listenToChildren,
}
},
})
</script>
<style></style>
子组件
代码示例:
<template>
<div style="color: brown">子组件</div>
<!-- 父传子使用方法和vue2相同 -->
<div>父组件传过来的值为:{{ title }}</div>
<button @click="sayToFather">向父组件说话</button>
</template>
<script lang="ts">
import { defineComponent } from "vue"
export default defineComponent({
name: "child",
props: {
title: {
type: String,
},
},
setup(props, context) {
// context作用是获取上下文对象,
// 如果setup写法为setup(props, { emit })的方式的话,下面的context可以省略
const sayToFather = () => {
const ask = "这是子组件"
context.emit("listen", ask)
}
return {
sayToFather,
}
},
})
</script>
<style></style>
vue2 vue3 父子传参的区别:
父传子
父组件:
<Child :num = "num"></Child>
import Child from "./xxx.vue"
不需要注册
子组件:
defineProps({
num: {
type: Number,
default: 30
}
})
像vue2中父传子那样,父组件通过自定义属性发送,子组件通过props接收。不过vue3中不同的是,父组件中引入子组件后,不需要注册可直接使用,子组件中通过defineProps方法接收。
子传父
父组件:
<Child @fn = "chanNum"></Child>
import Child from "./xxx.vue"
不需要注册
const chanNum = () => {}
子组件:
// 子传父时需要先定义好emit方法
const emit = defineEmits<{
(event: 'fn',n:number):void
}>()
const click = () => {
// 触发事件
emit("fn",n)
}
像vue2中子传父那样,子组件通过emit发送,父组件通过自定义事件接收。不过vue3中不同的是,父组件中引入子组件后,不需要注册可直接使用,子组件中通过defineEmits方法发送。