Using and understanding $refs in vue
Posted on: February 17, 2021 by Prince Chukwudire
Vue Refs are instance properties used to make reference to HTML elements in our vue application. In this guide, we will take a look at using $refs in accessing and manipulating DOM elements in vue.
<template>
<div>
<input type="text" ref="test" value="Original Ref" />
<button @click="changeValue" type="button">Change</button>
</div>
</template>
<script>
export default {
data() {
return {};
},
methods: {
changeValue() {
console.log("original value:", this.$refs.test.value);
this.$refs.test.value = "Changed Ref";
console.log("Changed value:", this.$refs.test.value);
},
},
};
</script>
We simply changed the value of the input tag by making reference to it. This is similar to what we would have done with a vanilla script as:document.getElementById('test').innerHTML = "changed Value"
Share on social media
//