Vue获取页面元素

Vue获取页面元素

Vue如何像jQuery一样获取页面DOM呢?

尽量不要直接操作DOM。

Vue可以在元素或者组件上使用 ref="refname" 来给元素或者组件一个锚点。

然后可以使用 this.$refs.refname 来获取元素。

在组件内部使用ref

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const app = Vue.createApp({})

app.component('base-input', {
template: `
<input ref="input" />
`,
methods: {
focusInput() {
this.$refs.input.focus()
}
},
mounted() {
this.focusInput()
}
})

在父组件中使用ref

比如在父组件中使用上面定义的子组件 base-input

1
2
<!-- 父组件中,在子组件上写ref -->
<base-input ref="usernameInput"></base-input>
1
2
// 父组件中获取子组件
this.$refs.usernameInput.focusInput()

评论