×

在Vue3 中 使用$ref 来获取元素

2021-07-21 13:28:22 Falcon

在常规js中我们需要用 querySelector()一类的方式来获取元素,在Vue中可以使用$ref

完整示例

<template>  
  <HelloWorld :msg="title"/>
  <input type="text" ref="myInput" />  
  <button @click="handleClick">Click</button>
</template>

<script>
import HelloWorld from '@/components/HelloWorld.vue'

export default {

  name: 'App',
  components: {
    HelloWorld
  },
  data() {
    return {
      title: "Hello Modal"
    }
  },
  methods: {
    handleClick() {
      console.log(this.$refs.myInput)
     this.$refs.myInput.classList.add('w3-red')
    }
  },
}
</script>


<style>

</style>

 点击后输出:

<input type="text">

操作如下:

 在模板里元素使用ref属性

<input type="text" ref="myInput" /> 

methods里需要这样取得

this.$refs.myInput

这会得到一个dom元素,可以使用普通的javascript方法操作,如:

this.$refs.myInput.classList.add('w3-red') //添加一个class
this.$refs.myInput.focus() //获得焦点

 

本文收录于