The function to focus on this.$refs[("p" + index)] element is not available

I need help transforming a div into an input box when clicked, allowing me to edit the post inside a loop.

Here is the button found on the post:

<a @click="setFocusEdit(index)" v-if="isAuthor(post)" href="#" >Edit Me</a>

And here is the specific div in question:

<div :ref="'p' + index"  class="post-description">
    {{post.description}}
</div>

This is the method I am using:

  setFocusEdit(index) {
    console.log('focusing on', index);

    this.$refs['p' + index].focus();
  },

However, I am encountering the following error message:

Uncaught TypeError: this.$refs[("p" + index)].focus is not a function

Could you provide guidance on resolving this issue?

Answer №1

When utilizing the v-for directive, it is recommended to use the ref attribute with a static name such as posts, which will give you an array of the referenced elements.

new Vue({
  el: '#app',
  data: function() {
    return {
      posts: [{
          title: "post 1",
          content: "content 1"
        },
        {
          title: "post 2",
          content: "content 2"
        }
      ],

    }
  },

  methods: {
    setFocusEdit(index) {


      this.$refs.posts[index].focus();
    }

  },
  mounted() {

  }

})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>




<div id="app">
  <div class='col-md-4 mt-3' v-for="(post, index) in posts" :key="index">
    <textarea readonly ref="posts" class="post-description">
      {{post.content}}
    </textarea>
    <a @click.prevent="setFocusEdit(index)" href="#">Edit Me</a>
  </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

Checking for the presence of the key name "item[]" within an object in AngularJs

I currently have an object called "obj" with two keys: "goal" and "item[]". It looks like this: var obj = {goal:"abc",item[]:"def"}; These keys and values are dynamically generated. Now here's the problem - I need to determine if these keys exist ...

Can the Twitter Bootstrap typeahead feature be used with an external data source?

Can the typeahead feature in version 2.0.3 of twitter-bootstrap work with a remote data source? You can check out the link for more information on the typeahead functionality: ...

Repeat the most recent AJAX request executed

I am currently working on refreshing a specific section of my application which is generated by an AJAX call. I need to target the most recent call that was made and rerun it with the same parameters when a different button is clicked. The data was initial ...

Having trouble with ReactJS rendering components?

FriendList.js var React = require('react'); var Friend = require('./friend.js'); var FriendList = React.createClass({ render: function() { return( <div> <h3& ...

Failed attempt to perform Ajax requests for REST API data

I am currently working on developing an application that requires a login through a REST API to retrieve a session id. To achieve this, I have set up a button that triggers a JavaScript function for making an AJAX call to authenticate the user. The result ...

Enhance tick labels in C3.js with supplementary information

I need a specific format for the tick: tick: { fit: true, multiline: false, outer: false, format: function (x) { var value = this.api.ca ...

What is the procedure for altering a particular element using ajax technology?

I have an AJAX request that updates the user information. I need to retrieve a specific value from the response and update the content of a specific element. For example, here is the element that needs to be changed: <div id="changeMe"><!-- New ...

Guide on adding checkboxes for each child component in a Vue ads table

<vue-ads-table :columns="fields" :rows="items" :selectable="true" @row-selected="onRowSelected" class="my-table" ...

Transfer the data from an XML element to generate a fresh element with an integrated value

I am looking to modify an XML file that contains multiple products by adding a new element with values from existing elements. Specifically, I want to add a new element to each product titled SKU, which should include the values of ProductOption, PurchaseO ...

Guide on transforming an array object for compatibility with MUI's Autocomplete field

I've encountered a challenge while attempting to transform my incoming object into a format suitable for MUI's Autocomplete component. Here is the current code snippet I am working with: const [contactList, setContactList] = useState([]); useEf ...

Discovering appropriate variable names within Vue components

I need to find all occurrences of specific variable names within my Vue components. I have a list of variables in my program and I want to check which components each variable is being used in. Here's an example: let x = ['test_one', &apos ...

The invocation of res.json() results in the generation of CastError

An issue occurs with CastError when using res.json() with an argument: CastError: Failed to cast value "undefined" to ObjectId for the "_id" field in the "Post" model Interestingly, using just res.status(), res.sendStatus(), or res.json() without argument ...

When converting to a React Functional Component using Typescript, an error occurred: The property 'forceUpdateHandler' could not be found on the type 'MutableRefObject<Spinner | null>'

Looking to convert the App component in this CodePen into a Functional component using Typescript. Encountering an error when attempting to run it: ERROR in src/App.tsx:13:14 TS2339: Property 'forceUpdateHandler' does not exist on type 'Mu ...

What is the best way to display the nested information from products.productId?

How do I display the title and img of each product under the product.productId and show it in a table? I attempted to store the recent transaction in another state and map it, but it only displayed the most recent one. How can I save the projected informa ...

Create a CSV document using information from a JSON dataset

My main goal is to create a CSV file from the JSON object retrieved through an Ajax request, The JSON data I receive represents all the entries from a form : https://i.sstatic.net/4fwh2.png I already have a working solution for extracting one field valu ...

Vue is struggling to load the component files

Lately, I've been encountering an error during webpack build that is causing some issues. ERROR There were 3 errors encountered while compiling The following relative modules could not be found: * ./components/component1.vue in ./resources/assets/ ...

Creating distinctive identifiers for individual function parameters in JavaScript using addEventListener

I am working on a for loop that dynamically generates elements within a div. Each element should trigger the same function, but with a unique ID. for(var i = 0; i < 10; i++) { var p = document.createElement("p"); var t = document. ...

Firebase 9: Access Denied - Realtime Database Security Breach

Currently working on a chat application using Vue3 and Firebase 9, everything is functioning well except for the delete function. An error message appears in the console: @firebase/database: FIREBASE WARNING: set at /message/-MzxBJXezscUw4PbEAys failed: pe ...

Save the result of a terminal command into an sqlite database

When I run a particular shell command in node js, the output is displayed on the console. Is there a method to store this output in a variable so that it can be POSTed to an Sqlite database? const shell = require('shelljs'); shell.exec('a ...

Issue with JavaScript causing circles to form around a parent div

I am struggling to position a set of circles around a parent div in my code. I want 6 circles to form a circle around the parent div, but they are not lining up correctly. Can someone help me identify what I'm doing wrong? var div = 360 / 6; var ra ...