vue3中父子组件之间传值的详解
首先我们回顾一下vue2中父子组件是怎么传值的,然后对比vue3进行详解。
一、vue2中父子组件传值
<!-- 父组件 -->
<template>
<div>
// name:父组件把值传给子组件test-child
// childFn:子组件传递值给父组件的自定义方法
<test-child :name="name" @childFn="parentFn"></test-child>
子组件传来的值 : {{message}}
</div>
</template>
<script>
export default {
data() {
return {
message: '',
name: '张三'
}
},
methods: {
// 接收子组件的传值
parentFn(payload) {
this.message = payload;
}
}
}
</script>
<!-- 子组件 -->
<template>
<div>
{{name}}
<input type="text" v-model="message" />
<button @click="click">发送消息给父组件</button>
</div>
</template>
<script>
export default {
props:{
name:{
type:String,
default:''
}
}
data() {
return {
message: '我是来自子组件的消息'
}
},
methods: {
click() {
// 1、childFn 组件方法名,请对照父组件
// 2、message是传递给父组件的数据
this.$emit('childFn', this.message);
}
}
}
</script>
上面的代码可以看到我们vue2中父子组件之间传值是通过prop传值给子组件,子组件通过$emit把值传递给父组件进行交互。那么我们下面看看vue3中是如何进行组件之间传值的。
二、provide & inject
vue3提供了provide() 和 inject() 两个方法,可以实现组件之间的数据传递。父级组件中使用 provide() 函数向子组件传递数据;子级组件中使用 inject() 获取父组件传递过来的数据。代码如下:
<!-- 父组件 -->
<template>
<div id="app">
<test-child></test-child>
</div>
</template>
<script>
import testChild from './components/testChild'
// 1. 按需导入 provide
import { provide } from '@vue/composition-api'
export default {
name: 'app',
setup() {
// App 根组件作为父级组件,通过 provide 函数向子级组件共享数据(不限层级)
// provide('要共享的数据名称', 被共享的数据)
provide('color', 'red')
},
components: {
testChild
}
}
</script>
<template>
<div>
<!-- 通过属性绑定,为标签设置字体颜色 -->
<h3 :style="{color: themeColor}">Level One</h3>
</div>
</template>
<script>
import { inject } from '@vue/composition-api'
export default {
setup() {
// 调用 inject 函数时,通过指定的数据名称,获取到父级共享的数据
const themeColor = inject('color')
// 把接收到的共享数据 return 给 Template 使用,进行数据渲染
return {
themeColor
}
}
}
</script>
通过上面的代码我们可以发现,vue3中数据传值更加简单了,不用再引入子组件标签上写属性,直接通过provide()设置指定的名称,可以在子组件中通过inject()拿到,是不是感觉很简单呢。