ai问答:使使用 Vue3 组合式API 和 TypeScript 父子组件demo

发布时间 2023-04-24 09:34:07作者: 让梦想纵横

这是一个使用 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属性注册子组件,并在模板中使用。子组件有自己的状态和数据逻辑。

两者之间的通信方式有:

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

修改父组件:

setup() {
  const msg = ref('Hello from Parent!')
  const text = ref('some text')
  return { 
    msg,
    text 
  }
}

修改子组件:

props: {
  text: String
}

然后在子组件模板使用{{ text }}接收。

  1. 子传父:通过父组件的ref获取子组件实例,然后调用实例方法
    修改父组件:
const child = ref(null)

return {
  msg,
  text,
  child
}

修改子组件:

setup() {
  const emitText = (text: string) => {
    (child.value as any).someMethod(text)
  }
}  

然后在父组件中定义someMethod方法接收:

const someMethod = (text: string) => {
  console.log(text)
}

在子组件中调用emitText('some text')就可以触发父组件的方法。