2

模板引用

 2 years ago
source link: https://v3.cn.vuejs.org/guide/component-template-refs.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

# 模板引用

该页面假设你已经阅读过了组件基础。如果你对组件还不太了解,推荐你先阅读它。

尽管存在 prop 和事件,但有时你可能仍然需要在 JavaScript 中直接访问子组件。为此,可以使用 ref attribute 为子组件或 HTML 元素指定引用 ID。例如:

<input ref="input" />

例如,你希望在组件挂载时,以编程的方式 focus 到这个 input 上,这可能有用:

const app = Vue.createApp({})

app.component('base-input', {
  template: `
    <input ref="input" />
  `,
  methods: {
    focusInput() {
      this.$refs.input.focus()
    }
  },
  mounted() {
    this.focusInput()
  }
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

此外,还可以向组件本身添加另一个 ref,并使用它从父组件触发 focusInput 事件:

<base-input ref="usernameInput"></base-input>
this.$refs.usernameInput.focusInput()

WARNING

$refs 只会在组件渲染完成之后生效。这仅作为一个用于直接操作子元素的“逃生舱”——你应该避免在模板或计算属性中访问 $refs

参考在组合式 API 中使用模板引用


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK