在 Vue 的 mounted 钩子函数中,操作子组件的 DOM 可以通过几种方式实现,具体取决于对子组件的访问方式。以下是一些常用的方法:
一、使用 ref 引用
- 定义 ref
在父组件中,给子组件添加一个 ref 属性,这样就可以在父组件中通过 this.$refs 访问到子组件的实例。
父组件示例:
<template>
<ChildComponent ref="child" />
</template>
<script>
export default {
mounted() {
// 访问子组件的 DOM 元素
const childDom = this.$refs.child.$el;
childDom.style.backgroundColor = 'lightblue'; // 操作子组件的 DOM
}
}
</script>
- 在子组件中
在子组件中,你可以使用 this.$el 来访问组件的根 DOM 元素。
子组件示例:
<template>
<div>
<p>子组件内容</p>
</div>
</temp