How can I access dynamically created input elements without using $refs, such as getting focus?

Is there a way to handle dynamically created inputs for editing purposes without using jQuery or vanilla JS all the time? Each input element has its own ID and is displayed through v-if when editing is triggered. However, Vue does not recognize them in refs, so $refs cannot be used. Any alternative solutions?

Answer №1

Typically, we start with a span element before making changes. In this situation, using v-show instead of v-if is preferred because the span still needs to be visible after editing. Each input field is directly linked to its corresponding span, allowing for actions like event.target.nextSibling.focus() to work effectively.

I find using event.target... more convenient than relying on $refs because introducing $refs can complicate the component's structure unnecessarily, while the former is only relevant within the context of the click event.

Answer №2

If you are looking to avoid vanilla js (with the exception of focusing), one suggestion is to transition your list elements into a component:

Vue.component('list-items', {
    template: 
    `<div>
        <button @click="edit">edit</button>
            <input v-if="editing" ref="input" type="text" :value="value" @input="$emit('input', $event.target.value)">
    </div>`,
    props: ['value'],
    data () {
    return {
        editing: false,
        }
    },
    methods: {
    edit () {
        this.editing = !this.editing
            if (this.editing) {
            this.$nextTick(() => {
                this.$refs.input.focus()
                })
            }
        },
    },
})

new Vue({
    el: '#app',
    data: {
        list: [{
            title: 'foo',
        }, {
            title: 'bar',
        }]
    },
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
    <list-items v-model="item.title" v-for="item in list"></list-items>
    <pre>{{ list }}</pre>
</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

Unable to retrieve options from a particular select box

Utilizing cheerio and nodejs to scrape all the countries listed on a website, I have implemented the following code: const rp = require('request-promise'); const cheerio = require('cheerio'); const options = { uri: 'https://u ...

"Having trouble with a single line conditional statement not functioning properly within data in a Vue

I am facing an issue with setting the data named isVendorOrAgent in a component. It should be either false or true> based on a property that the component receives. I noticed that when I tried setting this condition within the data section of the compon ...

Randomly positioning an image while the page is loading

I've been developing a portfolio website to showcase my design work, but I've encountered a minor issue. My goal is to have the images load in random positions and then make them draggable using Dragabilly. However, sometimes all the images end ...

Adding rows dynamically to multiple tables on a single page using a single function

I am facing a situation where I have multiple tables and a function that adds rows to these tables: <table id="table1" style=" border-collapse: collapse;"> <tr id="table1row1">... <tr id="table1row2">... <table id="table2" style=" bor ...

Having trouble with V-model while using CKEditor in vue.js sourced from the original?

Whenever I start a new vue project with CKEditor from source, I encounter an issue where the V-model for editor components does not function as expected. The ClassicEditor is unable to edit and update data properly. Is this a bug? vue.config.js const path ...

Error: react-testing-library throwing validateDOMNesting warning

Warning: validateDOMNesting(...): <tbody> cannot appear as a child of <div>. in tbody (created by TableBody) in TableBody (created by TableBody) in TableBody Inquiry: Is there a way to render the TableBody component within a table ...

What is the implication when Typescript indicates that there is no overlap between the types 'a' and 'b'?

let choice = Math.random() < 0.5 ? "a" : "b"; if (choice !== "a") { // ... } else if (choice === "b") { This situation will always be false because the values 'a' and 'b' are completely disti ...

Upon clicking, Vue triggers form validation in Laravel

I have encountered an issue that I am unable to solve by myself: Within my Laravel view, I have included a form in the following manner {!! Form::open(array('route' => ['reports.store', $project->id], 'data-parsley-validate& ...

Resetting the internal state in Material UI React Autocomplete: A step-by-step guide

My objective is to refresh the internal state of Autocomplete, a component in Material-UI. My custom component gets rendered N number of times in each cycle. {branches.map((branch, index) => { return ( <BranchSetting key={ind ...

Is there a way to include a vertical scrollbar within the modal dialog using Vuetify components?

Here is an example of my code: <div id="app"> <v-app> <v-content> <v-container> <v-dialog v-for='foo, k in foos' :key='foo.id' :close-on-content-click="false" ...

Chunk error ECONNREFUSED trigger

Encountered an issue while running through grunt. Getting a proxy error: Econnrefused when trying to run grunt serve. After running --verbose, it seems like the request is being blocked. I suspect it may be due to my organization's network setup, bu ...

Tips for implementing Mobx State Tree in your Vue JS project

Currently, I am in the process of developing an application using Vue and I am looking to utilize Mobx State Tree as a store management library. After some trial and error, I have managed to get something working, but it doesn't seem to be functioning ...

AngularJS: The delay in updating variable bindings following a REST API call

When utilizing a REST service, I wanted to implement a variable to show whether the service is currently loading or not. Controller $scope.loading = true; $http.get('/Something'). success(function(data, status, headers, config) ...

Tips for personalizing the NavigatorIOS's right side

Looking to create a navigation bar similar to Whatsapp's? I want to include a profile picture and call button on the right side of the bar. Any tips on how to achieve this look? Which properties should be used for this customization? Would it be bet ...

Delete JavaScript functions and events from memory once the JavaScript code has been removed from the HTML file

I am encountering a situation with my website where popups loaded via ajax also load JavaScript code, which I want to remove when the popup is closed. The main site code looks like this: <body> ... <div id="popup" style="display:none"> < ...

Display a preloader image while waiting for the content to load using jQuery or AJAX

Hey there, I could really use some help with a little issue. I've been trying to use the click() and load() functions to bring my content into a specific CSS class. $("#feed").click(function(){ $(".homefeed").load("feedcontainer.php"); ...

Functionality of the Parameters Object

As I transition from using the params hash in Rails to learning Node/Express, I find myself confused about how it all works. The Express.js documentation provides some insight: 'This property is an array containing properties mapped to the named rout ...

What is the process for obtaining the final element in an array of objects when a particular character is present in the value of a key?

Given the following array: arrOfOranges = [{ "kerp": "thisThing", "time": "@ rocks 3"}, { "kerp": "otherThing", "green": "blah"}, { "kerp": "thisThing", "time": "(countriesToTheStart ^"}, { "kerp": "anotherThing", "yellow": "row row"}, { "kerp": "anotherTh ...

Enhance text search functionality using AngularJS

Just starting to learn angularjs. Below is the code I've written: $scope.styles = [{"name":"walking"},{"name":"Food"},{"name":"culture"}] I have created a checkbox list <div ng-repeat="style in styles"> <input type="checkbox"> {{ ...

Attempting to output numerical values using Jquery, however instead of integer values, I am met with [Object object]

I am struggling to figure out how to display the value contained in my object after attempting to create a Calendar using Jquery. I attempted to use JSON.toString() on my table data, but it didn't solve the issue. Perhaps I am not placing the toString ...