vue3父组件控制子组件
时间: 2023-09-20 10:03:53 浏览: 44
在 Vue 3 中,你可以通过向子组件传递 props 或者使用 provide/inject 来实现父组件控制子组件的方式。
1. 使用 props:
在父组件中,通过 props 将需要控制的数据传递给子组件。子组件可以直接使用这些 props 数据,但不能直接修改。如果需要在子组件中修改这些数据,可以通过触发父组件的事件来实现。例如:
```vue
<template>
<div>
<child-component :value="parentValue" @update="updateParentValue"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
data() {
return {
parentValue: 'Hello'
};
},
components: {
ChildComponent
},
methods: {
updateParentValue(newValue) {
this.parentValue = newValue;
}
}
}
</script>
```
在子组件中,可以通过 `props` 接收父组件传递的数据,并通过 `$emit` 触发事件通知父组件进行更新。例如:
```vue
<template>
<div>
<button @click="updateValue">Update Value</button>
</div>
</template>
<script>
export default {
props: ['value'],
methods: {
updateValue() {
const newValue = 'Hello World';
this.$emit('update', newValue);
}
}
}
</script>
```
2. 使用 provide/inject:
在父组件中,通过 provide 提供需要共享的数据。子组件可以通过 inject 来获取这些数据,并在子组件中直接修改。注意,使用 provide/inject 可能会导致组件之间的紧密耦合,慎用。例如:
```vue
<template>
<div>
<child-component></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
import { provide } from 'vue';
export default {
data() {
return {
parentValue: 'Hello'
};
},
components: {
ChildComponent
},
setup() {
provide('parentValue', this.parentValue);
}
}
</script>
```
在子组件中,使用 inject 来获取父组件提供的数据,并直接进行修改。例如:
```vue
<template>
<div>
<button @click="updateValue">Update Value</button>
</div>
</template>
<script>
import { inject } from 'vue';
export default {
setup() {
const parentValue = inject('parentValue'); const updateValue = () => {
parentValue.value = 'Hello World';
};
return { updateValue };
}
}
</script>
```
这样,通过 provide/inject 的方式,父组件提供了一个可在子组件中直接修改的数据对象。