Vue3教程:模板引用

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

尽管存在 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()
  }
})

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

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

WARNING

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

作者:terry,如若转载,请注明出处:https://www.web176.com/vue3/6253.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2022年7月7日 上午11:38
下一篇 2022年7月8日 上午10:51

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注