Refs are one of the most important feature of Vue js. Be it calling a method of another component or assigning property of one element to other, as you grow to become an immaculate vue developer, you'll find the immense need and rich potentiality of refs.
Suppose you want to customize things but there aren't default way of doing so. This is where vue refs could be useful. For example if you want to style input file type and you are not using any component based design, this could be of great help. So, lets dive in.
<div class="container"> <div class="input-file" @click="uploadFile"> <input type="file" style="display:none;" ref="fileUploader" /> Click the image to upload file .... <br /> <img src="uploadImg.png" style="width:400px;height:200px;"> <p class="text"> The input type file below will be hidden but we have assigned it a reference. So when this div is clicked we will create an event so as to replicate the input file is clicked </p> </div> <script> new Vue({ el:'.container', methods: { uploadFile() { this.$refs.fileUploader.click() } } }) </script> </div>
Js Fiddle Link
Calling a method of inside of a component from another component
Refs are also helpful when you need to call a method inside of a child component you imported from a component you are working on right now. For example you imported a child component passed a prop value (x=2;y=3), and there is a method that returns the sum of the value of the props you just passed but you need to call the method of child component from another component. Thanks to ref, it is so easy than you may have thought.
Example: Child component<template> <div> {{sum}} </div> </template> <script> export default { props:["x","y"], data(){ return{ sum:null } }, methods:{ addValues(){ this.sum= this.x + this.y } } </script>
<template> <div> <child-component x="3" y="2" ref="vueRef" /> <button @click="callChildMethod()"> Call the method inside of Child </button> </div> </template> <script> import ChildComponent from '../ChildComponent' export default { components: {ChildComponent}, data(){ return{} }, methods:{ callChildMethod(){ this.$refs.vueRef.addValues.click(); } } </script>
Comments
Post a Comment