全部学科
Python全栈
python
NodeJS全栈
nodejs
📅 2026-05-20 5 分钟 ✍️ juanwangdev

beforeMount与mounted

这两个钩子处理组件挂载阶段的逻辑。

beforeMount

JavaScript
export default {
  beforeMount() {
    // 模板编译完成,但未挂载到 DOM
    console.log(this.$el) // 虚拟 DOM
  }
}

mounted

JavaScript
export default {
  mounted() {
    // 组件已挂载到真实 DOM
    console.log(this.$el) // 真实 DOM 元素
    
    // 可执行 DOM 操作
    this.$refs.input.focus()
    
    // 可初始化第三方库
    this.chart = new Chart(this.$refs.chart)
  }
}

Composition API

JavaScript
import { onMounted, ref } from 'vue'

export default {
  setup() {
    const input = ref(null)
    
    onMounted(() => {
      input.value.focus()
    })
    
    return { input }
  }
}

典型用途

钩子可访问 DOM典型用途
beforeMount否(虚拟 DOM)很少使用
mountedDOM 操作、第三方库初始化

mounted 不保证子组件也已挂载,如需等待所有子组件挂载完成,使用 this.$nextTick

要点总结

  • beforeMount 模板已编译但未挂载到 DOM
  • mounted 可访问真实 DOM
  • DOM 操作和第三方库初始化在 mounted 中进行
  • Composition API 使用 onMounted
想在手机上练习这篇文章的配套题目?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码
← 上一篇 beforeCreate与created
下一篇 → beforeUpdate与updated
扫码体验小程序
加载中
想在手机上刷题学习?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码