ai问答:使用 Vue3 组合式API 和 TS 父子组件共享数据

2023-06-15,,

这是一个使用 Vue3 组合式 API 和 TypeScript 的简单父子组件共享数据示例

父组件 Parent.vue:

<template>
<div>
<p>{{ msg }}</p>
<Child />
</div>
</template> <script lang="ts">
import { ref } from 'vue'
import Child from './Child.vue' export default {
components: { Child },
setup() {
const msg = ref('Hello from Parent!')
return { msg }
}
}
</script>

子组件 Child.vue:

<template>
<div>
<p>Hello, my name is {{ name }}</p>
</div>
</template> <script lang="ts">
import { ref } from 'vue' export default {
setup() {
const name = ref('John')
return { name }
}
}
</script>

父组件通过components属性注册子组件,并在模板中使用;子组件有自己的状态和数据逻辑。

两者之间的通信方式有:

    父传子:通过子组件的props接收父组件传递的数据

修改父组件:

<template>
<div class="parent">
<p>{{ msg }}</p>
<Child :text="text"/>
</div>
</template> <script lang="ts">
import {ref} from 'vue'
import Child from '@/components/Child.vue' export default {
components: {Child},
setup() {
const msg = ref('Hello from Parent!')
const text = ref('some text')
return {msg, text}
}
}
</script> <style>
.parent {
background-color: #ffffff;
}
</style>

修改子组件:

<template>
<div class="child">
<p>Hello, my name is {{ name }}</p>
<p>{{ text }}</p>
</div>
</template> <script lang="ts">
import {ref} from 'vue' export default {
props: {
text: String
},
setup(props: { text: string }) {
console.log(props)
const name = ref('John')
return {name}
}
}
</script> <style>
.child {
background-color: #ffffff;
}
</style>

然后在子组件模板使用{{ text }}接收,也可以在setup中使用props

    子传父:通过自定义事件@change,获取子组件传参

修改父组件:

<template>
<div class="parent">
<p>{{ msg }}</p>
<Child :text="text" @change="onChange"/>
<p>{{childText}}</p>
</div>
</template> <script lang="ts">
import {ref} from 'vue'
import Child from '@/components/Child.vue' export default {
components: {Child},
setup(props: any, {expose}: any) {
const msg = ref('Hello from Parent!')
const text = ref('some text')
const childText = ref("") const onChange = (text: string) => {
childText.value = text;
} return {msg, text, childText, onChange}
}
}
</script> <style>
.parent {
background-color: #ffffff;
}
</style>

修改子组件:

<template>
<div class="child">
<p>Hello, my name is {{ name }}</p>
<p>{{ text }}</p>
</div>
</template> <script lang="ts">
import {ref} from 'vue' export default {
props: {
text: String
},
emits: ['update'],
setup(props: { text: string }, {emit}: any) {
console.log(props);
const name = ref('John')
emit('change', 'emit change') return {name}
}
}
</script> <style>
.child {
background-color: #ffffff;
}
</style>

在子组件中调用emit('change', 'emit change')就可以触发父组件的方法。

ai问答:使用 Vue3 组合式API 和 TS 父子组件共享数据的相关教程结束。

《ai问答:使用 Vue3 组合式API 和 TS 父子组件共享数据.doc》

下载本文的Word格式文档,以方便收藏与打印。