By Nwose Lotanna

Translation: Crazy geek

Original text: blog.logrocket.com/how-to-use-…

Reproduced without permission

In this article, you’ll learn how to reference HTML elements in a component in vue.js.

The premise condition

This article is intended for all developers using Vue, including beginners. Before you read this article, you should have a few prerequisites:

  • Node.js 10.x or later. Run at a terminal or command promptnode -vTo verify your version
  • NPM 6.7 or later
  • Code editor; I highly recommend Visual Studio Code
  • Install the latest version of Vue globally on your machine
  • Install Vue CLI 3.0 on your computer. First of all usenpm uninstall -g vue-cliUninstall the old CLI version and usenpm install -g @vue/cliInstall the new version.
  • Download the Vue Starter program at github.com/viclotana/v…
  • Unzip the downloaded project, switch to the directory it made, and run itnpm installTo keep all dependencies up-to-date

What is a REF?

Ref is an instance attribute of Vue that is used to register or indicate references to HTML elements or child elements in an application template.

If you add a REF attribute to an HTML element in a Vue template, you can reference that element or even its child elements in a Vue instance. You can also access the DOM element directly, which is a read-only property and returns an object.

Why is ref important?

The ref attribute is critical to selecting the DOM element that contains it by serving as a key in the parent $ref attribute. For example, placing a ref attribute inside an input element exposes the parent DOM node as this.$refs.input, or as this.refs[“input”].

DOM elements can be easily manipulated by defining methods on references to specific elements. A typical example is to add focus to an input element with this:

this.$refs["input"].focus()
Copy the code

In this way, refs are used like document.querySelector(‘.element’) in JavaScript or $(‘.element’) in jQuery. $refs can be accessed inside and outside the vue.js instance. But they are not data attributes, so they are not responsive.

They don’t show up at all when the template is checked in the browser, because it’s not an HTML attribute, just a Vue template attribute.

Demo

If you’ve been following this article since the beginning, you should have downloaded the Vue Starter project and opened it on VS Code by now. Open the Components folder and copy the following code into the test.vue file:

<template> <div> <h2>Hello this is for refs man! </h2> <p>You have counted {{this.counter}} times</p> <input type="text" ref="input"> <button @click="submit">Add 1 to counter</button> </div> </template> <script> export default { name: 'Test', data(){ return { counter: 0 } }, methods: { submit(){ this.counter++; console.log(this.ref) } } } </script>Copy the code

Now run it in the development server with the following command:

npm run serve
Copy the code

You’ll see that the user interface displays a simple counter that is updated when clicked, but when you open the developer tools in your browser, you’ll notice that it doesn’t log.

It’s important to use the syntax correctly because it means that Vue doesn’t see this as an error, and it does. Based on what we already know about Vue Refs, they return an object, but judging by the undefined response, something is wrong. Copy the following code into the test.vue file:

<template>
  <div>
    <h2>Hello this is for refs man!</h2>
    <p>You have counted {{this.counter}} times</p>
    <input type="text" ref="input">
    <button @click="submit">Add 1 to counter</button>
  </div>
</template>
<script>
export default {
  name: 'Test',
  data(){
    return {
      counter: 0}},methods: {
    submit(){
      this.counter++;
      console.log(this.$refs)
    }
  }
}
</script>
Copy the code

When you run and examine it, you will see that an object is now returned:

A quick look at the code block reveals the correct syntax: in the template it is called ref, but when we reference it in the Vue instance it is called $refs. This is important when undefined is not returned. You can access every possible attribute of a reference element, including elements in the template.

Next, record some of the properties we might be interested in. The contents of your test.vue file should now read:

<template>
  <div>
    <h2>Hello this is for refs man!</h2>
    <p>You have counted {{this.counter}} times</p>
    <input type="text" ref="input">
    <button @click="submit">Add 1 to counter</button>
  </div>
</template>
<script>
export default {
  name: 'Test',
  data(){
    return {
      counter: 0}},methods: {
    submit(){
      this.counter++;
      console.log(this.$refs)
    }
  }
}
</script>
<style scoped>
p , input.button{
  font-size: 30px;
}
input.button{
  font-size: 20px;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
Copy the code

Your browser should look like this:

Display elements

To display HTML elements in the DOM, enter the Submit method and change the methods code to the following:

methods: {
    submit(){
      this.counter++;
      console.log(this.$refs.input)
    }
  }
Copy the code

Input here is the name of the reference you created in the element earlier (ref=”input”). It can be any name you choose.

Displays the entered value

To display the input value for an HTML element (a string typed into a text box in the user interface), enter the Submit method and change the code to:

methods: {
    submit(){
      this.counter++;
      console.log(this.$refs.input.value)
    }
  }
Copy the code

This displays the string you typed, although vanilla JavaScript and jQuery can do the same thing.

Displays the URL of the element

Enter the Submit method and change the code to:

methods: {
    submit(){
      this.counter++;
      console.log(this.$refs.input.baseURI)
    }
}
Copy the code

There are many other object information that can be returned by ref.

Conditional processing

The vue.js refs can also be used to output multiple elements inside a DOM element, such as conditional statements using the V-for instruction. Refs returns an array of items instead of objects when called. To illustrate this, create a simple list like this:

<template>
  <div>
    <p v-for="car in 4" v-bind:key="car" ref="car"> I am car number {{car}}</p>
    <button @click="submit">View refs</button>
  </div>
</template>
<script>
export default {
  name: 'Test',
  data(){
    return {
    }
  },
  methods: {
    submit(){
      console.log(this.$refs)
    }
  }
}
</script>
Copy the code

When you run it again in the development server, it will look like this:

You can find it at GitHub (github.com/viclotana/v…

conclusion

This article explains how to reference HTML elements in the DOM in vue.js. You can now access and record all elements, such as values, child nodes, data attributes, and even its base URL.

We also learned how to achieve this goal. Note that refs are populated after the Vue instance is initialized and the component is rendered, so the use of refs in computed properties is discouraged because it can manipulate child nodes directly.

Welcome to pay attention to the front end public number: front end pioneer, receive front-end engineering practical toolkit.