企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持知识库和私有化部署方案 广告
# 模板refs > 本章节需要掌握组件基础 即使有了`props`和事件,有时候你仍然想直接使用JavaScript访问子组件。为了达到这个目的,你可以为组件或HTML标签用`ref`属性分配一个关联的ID。例如: ~~~html <input ref="input" /> ~~~ 有时候这很有用,比如你想在组件挂载时用程序将光标聚焦到该文本框: ~~~ const app = Vue.createApp({}) app.component('base-input', { template: ` <input ref="input" /> `, methods: { focusInput() { this.$refs.input.focus() } }, mounted() { this.focusInput() } }) ~~~ > [zy] 这有点像DOM操作了吧? 同时你也可以给这个组件实例加一个`ref`,然后就能触发父组件调用方法来聚焦这个文本框: ~~~html <base-input ref="usernameInput"></base-input> ~~~ ~~~ this.$refs.usernameInput.focusInput() ~~~ >[warning]`$refs`只在组件被渲染后才存在,你应避免在模板和计算属性中使用它。