vue3父组件怎么修改子组件的内容
时间: 2023-09-16 08:08:05 浏览: 50
在Vue3中,要修改子组件的内容,可以通过`ref`和`props`的方式来实现。
首先,在父组件中使用`ref`来获取子组件的实例,在子组件中使用`props`将需要修改的内容传递给子组件。
父组件示例代码:
```html
<template>
<div>
<button @click="changeMsg">修改子组件的内容</button>
<ChildComponent ref="child" :message="msg"></ChildComponent>
</div>
</template>
<script>
import { defineComponent, ref } from 'vue'
import ChildComponent from './ChildComponent.vue'
export default defineComponent({
components: {
ChildComponent
},
setup() {
const msg = ref('Hello World')
const changeMsg = () => {
// 通过 ref 获取子组件的实例
const childComponent = this.$refs.child
if (childComponent) {
// 调用子组件的方法修改内容
childComponent.changeMessage('你好,Vue3!')
}
}
return {
msg,
changeMsg
}
}
})
</script>
```
子组件示例代码:
```html
<template>
<div>{{ message }}</div>
</template>
<script>
import { defineComponent, ref } from 'vue'
export default defineComponent({
props: {
message: {
type: String,
default: 'Hello World'
}
},
setup(props) {
const message = ref(props.message)
const changeMessage = (newMessage) => {
message.value = newMessage
}
return {
message,
changeMessage
}
}
})
</script>
```
在父组件中,通过`ref`获取子组件的实例,然后调用子组件的`changeMessage`方法,将新的内容传递给子组件,从而修改子组件的内容。