在 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