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

Utilize the HTML canvas to sketch on an image that has been inserted

I have a HTML canvas element within my Ionic application. <canvas id="canvas" color="{{ color }}" width="800" height="600" style="position:relative;"></canvas> Within this canvas, I am loading an image. Below is the code snippet from the con ...

What is the reason for the getter not being able to retrieve the value

I am experiencing an issue with a getter that returns an array of objects. The challenge I face is that I need to display past and current warnings in separate components. The getter currently only retrieves the current warning and ignores any past warnin ...

Choosing different elements using identical classes in JQuery

Struggling with a coding problem that seems like it should be an easy fix, but can't quite figure it out. The HTML code I have is as follows: <section class="actualite"> <div class="actualite-text"> <h3 class="title"&g ...

Does JSX have an API that can handle self-closing tags, such as <br>, if they are not closed properly?

For my latest project, I've been working on a ReactJS component using JSX and it looks something like this: <script type="text/jsx"> var HelloWorld = React.createClass({ render: function() { return ( < ...

React-native - Dropdownpicker - Error: Unable to retrieve label for selected choice

I'm encountering an issue with DropDownPicker in my react-native project during page load Here is the code snippet where I am using DropDownPicker: <DropDownPicker items={[ { la ...

Learn how to easily upload multiple files from various upload points onto a single page using Node.js and express-fileupload

After searching on various platforms, including StackOverflow, I couldn't find a solution that fits my specific scenario. I've been struggling for hours to resolve this issue... In my handlebars page, there is an option for the user to upload fi ...

What is the process for altering an SVG image following a click event in Javascript?

I have a tab within a div that includes text and an svg icon as shown herehttps://i.stack.imgur.com/TjwIK.png When I click on the tab, it expands like this https://i.stack.imgur.com/XNuBi.png After expanding, I want the svg icon to change to something e ...

Producing asynchronous JavaScript events using a browser extension (NPAPI)

Currently in the process of developing a web browser plugin using NPAPI. The issue I am facing is that my plugin requires a worker thread to handle certain tasks, and I need to pass events back to JavaScript as the worker progresses. However, due to the N ...

ng serve issue persists even after resolving vulnerabilities

Can anyone assist me in resolving why I am unable to start my project after fixing 3 high vulnerabilities? I ran npm audit to identify the vulnerabilities and then used npm install --save-dev @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Automatically choose radio buttons within an li element in a loop

Hey there, I'm new to SO and this is my first question. As a bit of a newbie, I found this jquery code snippet on another SO answer that I want to use. The function I'm aiming for is the same, but the markup structure in my HTML is different bec ...

The NodeJS server encountered an issue when attempting to load the JavaScript modules

Hey everyone. I'm currently using Node.js and Express.js for the back end of my web application, but I keep running into issues with the server trying to bind references in the source code. Here's the structure of my app: src/ - static/ - ...

Show information - press the button on the current PHP page

After successfully reading files via PHP from a directory and dynamically creating a drop-down menu to view the file content, I have a query. Is there a way to display the text files' content on the same page without calling another PHP page? I know t ...

"Getting Started with Vue.js: Exploring the setup() and mounted

I recently started using Vue.js and am currently tackling a project. In my setup(), I've declared some constants, with one of them named "c". I found that I can still use console.log(this.c) in mounted() to print out the constant, but when I attempt t ...

retrieving multiple values in ajax call and processing them in controller function

I'm facing a challenge in Laravel when it comes to sending multiple input options (generated by a foreach loop) through an ajax call. The goal is to send multiple values and loop through them in the ajax call to effectively pass them to the controller ...

configure various search parameters simultaneously during the rendering process

Incorporating a Tree component from mui v5, I am aiming to include searchParams for the selected and expanded nodes. This task is accomplished using the useSearchParams hook from React Router (v6). The issue arises when both the selected and expanded even ...

Determining the appropriate generic type in Typescript

In my code, there is a method designed to extend an existing key-value map with objects of the same type. This can be useful when working with database query results. export function extendWith< T extends { id: string | number }, O = | (T[" ...

Troubleshooting Database Saving Problem with Vue.js and Ruby on Rails

Trying to configure a nested form with Vue.js in a Rails application to save ingredients for a recipe. While all other details of the ingredients are saving correctly, the ingredient name (from an input field) is not getting saved in the database. How can ...

The navigation bar options are not collapsing as intended

When I resize my page to width:750px;, my navigation bar is not collapsing the items. Despite trying to edit my CSS, I am still clueless. Here is my live page. This is the CSS for my slidebar: @media (max-width: 480px) { /* Slidebar width on extra small ...

Invoking vscode Extension to retrieve data from webview

One task I'm currently working on involves returning a list from the extension to be displayed in the input box of my webview page. The idea is for a JavaScript event within the webview to trigger the extension, receive the list object, and then rend ...

Click the button to reset all selected options

<form method="post" action="asdasd" class="custom" id="search"> <select name="sel1" id="sel1"> <option value="all">all</option> <option value="val1">val1</option> <option value="val2" selected="selected"> ...