Is it possible that binding a ref is not functional in vue.js?

Whenever I use v-bind to bind an element reference with :ref="testThis", it appears to stop functioning. Take a look at this working version:

<template>
    <div>
        <q-btn round big color='red' @click="IconClick">
        YES
        </q-btn>
        <div>
            <input
                ref="file0"
                multiple
                type="file"
                accept=".gif,.jpg,.jpeg,.png,.bmp,.JPG"
                @change="testMe"
                style='opacity:0'
            >
        </div>
    </div>
</template>

<script>
import { QBtn } from 'quasar-framework'

export default {
  name: 'hello',
    components: {           
         QBtn
    },
    data () {
    return {
      file10: 'file0'
    }
  },
  methods: {
    IconClick () {
      this.$refs['file0'].click()
    },
        testMe () {
            console.log('continue other stuff')
        }
    }
}

</script>

Now, take a look at the version that DOES NOT work, this one:

<template>
    <div>
        <q-btn round big color='red' @click="IconClick">
        YES
        </q-btn>
        <div>
            <input
                :ref="testThis"
                multiple
                type="file"
                accept=".gif,.jpg,.jpeg,.png,.bmp,.JPG"
                @change="testMe"
                style='opacity:0'
            >
        </div>
    </div>
</template>

<script>
import { QBtn } from 'quasar-framework'

export default {
  name: 'hello',
    components: {           
         QBtn
    },
    data () {
    return {
      file10: 'file0'
    }
  },
  methods: {
    IconClick () {
      this.$refs['file0'].click()
    },
        testThis () {
            return 'file0'
        },
        testMe () {
            console.log('continue other stuff')
        }
    }
}

</script>

The first example works fine, but the second one throws an error:

TypeError: Cannot read property 'click' of undefined
    at VueComponent.IconClick

I need to have a bound reference in order to vary it based on a list index (not shown here). Why is the binding not working and throwing an error?

Answer №1

After researching in the vue documentation, I came across a statement that caught my attention: " $refs is also non-reactive, therefore you should not attempt to use it in templates for data-binding."

This resonates with my current situation.

The specific issue of 'how to reference an item of a v-for list' proves to be challenging without utilizing a bound ref since Vue aggregates all similar item-refs into an array, which results in losing the (v-for index) order.

I have another complex single file component where I successfully implemented this code snippet:

:ref="'file' + parentIndex.toString()"

In this particular case, the only deviation from the previous example is that parentIndex is a property of the component.

Overall, the topic seems somewhat confusing because according to information found here, binding refs was permitted in earlier versions of Vue.

EDIT: Successfully triggering the method using testThis(). You can see it working on this link.

Answer №2

To utilize a method, you must use the invocation parentheses within the binding. This informs Vue that you want to bind the result of the call rather than the function itself.

             :ref="testThis()"

The following snippet seems to function as expected. I opted for using a computed instead of a method.

new Vue({
  el: '#app',
  data() {
    return {
      file10: 'file0'
    }
  },
  computed: {
    testThis() {
      return 'file0';
    }
  },
  methods: {
    IconClick() {
      this.$refs['file0'].click()
    },
    testMe() {
      console.log('continue other stuff')
    }
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app>"
  <q-btn round big color='red' @click="IconClick">
    YES
  </q-btn>
  <div>
    <input :ref="testThis" multiple type="file" accept=".gif,.jpg,.jpeg,.png,.bmp,.JPG" @change="testMe" style='opacity:0'>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update my function to be asynchronous by changing async: false to async: true using JQuery and Ajax

I've created a function in a JavaScript class that accesses a PHP file to retrieve information from a database. Although this function works well, I attempted to set the property async: true, and it caused the function to stop working. (I received th ...

When conditions are met, all items are added to the array

In my Angular app, I have a user list that I am trying to filter based on the condition age > 45. However, all users are being pushed into the validForScheme array instead of just those meeting the condition. I am unable to figure out what is going wron ...

Guide on Generating SAS Token for Azure Table Storage in a jQuery Application

I am currently working on a jQuery web application that requires read-only access to an Azure Table Storage, fetching one record at a time by passing in the PartitionKey and RowKey. To simplify my code, I have integrated the Azure Storage JavaScript Client ...

Undefined TypeScript Interface

Here's my situation: public retrieveConnections() : IUser[] { let connections: IUser[]; connections[0].Id = "test"; connections[0].Email = "asdasd"; return connections; } I know this might be a dumb question, but why is connecti ...

Unable to conceal the scrollbar while keeping the div scrollable

I've been attempting to implement the techniques outlined in the guides on this site, but I'm encountering difficulty hiding the scroll bar while still maintaining scrolling functionality! My current approach involves setting the parent as relat ...

Next.js, Knex, and SWR: Unusual issue disrupting queries

When making API requests using Next API routes and interacting with Knex + MySQL, along with utilizing React and SWR for data fetching, I encountered a strange issue. If a request fails, my SQL queries start to append ", *" to the "select" statement, causi ...

Utilize Vue Slot with variable names for dynamic integration

My current dilemma involves a unique component called TableContainer, featuring dynamically named slots. // ... <td class="..."> <slot :name="'statuses-' + item.id" /> </td> <td class=""> ...

Enhancing middleware chaining in Express

Below is the code for my Express configuration: var server = express() .use(express.cookieParser()) .use(express.session({secret: buffer.toString('hex')})) .use(express.bodyParser()) .use(express.static('./../')); serv ...

Maximizing the potential of Next JS 13 Server Components

Exploring the updates in Next JS 13, I have found it intriguing that every component is now a server component by default. This concept has been puzzling for me as I try to grasp how to effectively leverage this feature. For instance, my current challenge ...

The resource in CosmosDB cannot be found

I have successfully stored documents on Cosmos, but I am encountering an issue when trying to retrieve them using the "read" method. this.cosmos = new CosmosClient({ endpoint: '' key: '' }); this.partitionKey = '/id' thi ...

Storing the order of jQuery UI Sortable in the WordPress Admin Panel

My goal is to customize the order of taxonomy terms for each individual post in Wordpress. I have created a metabox on the EDIT POST page that contains custom taxonomy terms and made them sortable using JQuery. Here is my setup on the Wordpress backend: ...

Stop the selection of text within rt tags (furigana)

I love incorporating ruby annotation to include furigana above Japanese characters: <ruby><rb>漢</rb><rt>かん</rt></ruby><ruby><rb>字</rb><rt>じ</rt></ruby> However, when attemp ...

What is the best way to design a Global Navigation menu for websites?

For example, I am looking to integrate a Navigation menu into my website using just one file. I have considered using PHP or creating an HTML frame, but I am wondering what the current industry standard is for professionals. Any insights? ...

Dynamically loading Ember templates with asynchronous requests

I need a way to dynamically load HTML content from another file using the code below: App.MainView = Ember.View.extend({ template:function(){ $.ajax({ url: 'views/main.html', dataType: 'text', async: false, ...

Revamp your code by utilizing ES6 class to replace multiple if statements in Javascript

Currently, my code is filled with numerous if statements and I am considering a switch to classes in ES6. However, Javascript isn't my strong suit... so PLEASE HELP ME..! Previous code: //example code function first(){ console.log('first sce ...

Angularjs 2 Error: Unable to access the 'infos' property of an undefined object using the Http Client

I've been working on an AngularJS app for about a week now, developing a backoffice application for my service. My main challenge lies in using data retrieved from a remote server. I have 4 HTTP GET requests in my app - 2 of them fetching lists of us ...

Obtain the URL value using jQuery and place it inside a <span> element

How can I insert a href value into the span tag like this? <p class="name"> <a download="adja-lo.pdf" title="adja-lo.pdf" href="http://localhost/MatrixDRSnews/apps/Matrix/server/php/files/adja-lo.pdf">adja-lo.pdf</a> </p> ...

How to retrieve an element using a dynamically generated class name in Vue.js

<v-data-table :headers="menuheaders" //this menus from api response :items="menus" item-key="usersmenu_menuid" items-per-page="1000" hide-default-footer="" class="elevation-1" > <template v-s ...

Adding JavaScript files to a project in Ionic2 with Angular2 integration

I'm looking to incorporate jQuery into my Ionic2 app, which requires loading several JavaScript files: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script type="text/j ...

Check to see if a div element with an id that contains a numerical value has been

My HTML code contains X elements, each with an ID in the format: viewer_mX In this case, X is a number ranging from 1 to m (where m varies). I am looking to utilize JavaScript to retrieve the respective element's number X when a user clicks on one ...