Is it feasible to assign a value to a Vue component within a function at a later time?

Currently working on an autocomplete feature and I have encountered a hurdle. The issue is with binding the element using v-model:

v-model="input"

When I bind the element using v-model or v-bind, the input element ends up with a blank value. What I actually want is for the element to display an old value or a value fetched from the database, as shown in the code snippet below. I am looking to bind the element's value to my variable named "input" only after the page has fully loaded with data from the DB. Although the code below is functional, I find myself resorting to using document.getElementById to update the element with the new value.

<div id="spvs" class="uk-form-controls">
     <input v-on:input="input = $event.target.value" v-on:keyup="getCompanies" name="company" id="company" class="uk-input {{$errors->has('company') ? ' uk-form-danger' : ''}}" placeholder="Enter company name" 
            value="{{ old('company') || $errors->has('company')
                ? old('company') 
                : $property->getCompanyName()
            }}">

    <div v-if="spvs.length > 0" class="tm-autocomplete-box">
        <ul class="uk-list uk-list-striped tm-autocomplete-list">
            <li v-for="(spv, key) in spvs" @click="complete(key)"><span uk-icon="plus-circle" class="uk-margin-right"></span> @{{ spv.name }}</li>
        </ul>
    </div>
</div>

Ideally, I would like to bind the element value to my 'input' variable when the user clicks on one of the autocomplete items, triggering the 'complete' function.

methods:{
        complete: function(key){
            this.input = this.spvs[key].name;
            document.getElementById('company').value = this.input;
            this.spvs = '';
        },

In essence, I am looking to replace the line below with a more efficient binding method:

document.getElementById('company').value = this.input;

Answer №1

Are you looking to pre-populate your input with an old value upon component initialization and then update the value? You can achieve this using v-model as shown below:

Upon component load, the input will display the desired old value and allow for updates:

<div id="app">
  <input type="text" v-model="oldValue">
</div>

new Vue({
  el: "#app",
  data: {
    oldValue: 'value from Database'
  }
})

If you prefer an alternative approach, here is another method:

<div id="app">
  <input type="text" :value="oldValue" @input="changeValue">
  <hr>
  The value of input is: {{oldValue}}
</div>

new Vue({
  el: "#app",
  data: {
    oldValue: 'value from Database'
  },
  methods: {
    changeValue(newValue) {
      this.oldValue = newValue.target.value
    }
  }
})

See the first example in action

See the second example in action

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

Exploring the intricacies of managing nested data in a Firebase Database (web)

I understand this question may have similarities to others already asked, so my apologies in advance. I am seeking a clear, up-to-date solution that aligns with my expectations. https://i.sstatic.net/dQ9ih.jpg If I have an object labeled "Item One", how ...

A guide on extracting data from an uploaded JSON file in a React and Next.js application

Users have the ability to upload a JSON file by clicking on the button provided (shown below). https://i.sstatic.net/jndOd.png Once the JSON file is uploaded, the content is stored into a variable or a state. let fileRef = useRef(); const uploadHandle ...

Upon successful authentication, the WebAuthenticationBroker.authenticateAndContinue function does not activate the app

I'm attempting to implement Facebook, Twitter, and Google login using WebAuthenticationBroker.authenticateAndContinue. The authentication page is displayed successfully, but once the authentication is complete, the activated event is not triggered and ...

Clicking a button triggers a call to an API endpoint, resulting in a message being displayed on the client side

I am struggling with a simple school assignment that involves creating an API endpoint in Node.JS to respond to a GET request. The goal is that when clicking a button in the HTML file, the API should be called and display the message "Hello World" along wi ...

Having trouble connecting and establishing an onmousemove event?

I am looking to implement a mouse move event handler in my three.js project, but I have been struggling to connect it with the mouse and make it work. It would be greatly appreciated if someone could provide guidance on how to achieve this. I am not sure ...

Utilizing controller variables within ng-repeat in AngularJS

As I delve into learning AngularJS, I am attempting to utilize a variable from the controller in an ng-repeat without using scope. However, my code is not functioning as expected. Can someone help me identify and correct my mistake? Below is the snippet ...

Guide to fetching a string using Angular's http client?

I am facing an issue with calling a server that returns a csv file as text. I am using Angular's HttpClient and I need to prevent it from trying to cast the csv file to JSON. I tried setting the responseType to 'text' in the httpOptions, but ...

The functionality of jQuery's .hide method is not effective in this specific scenario

HTML section <div class="navigation-bar"></div> Jquery & JavaScript section function hideUserDiv(){ $('.ask-user').hide(); } var ask = '<div id="ask-user" style="block;position:absolute;height:auto;bottom:0;top ...

Is it possible to delete browsing history in Express using node.js?

Upon user login, I store user information in browser sessions on the client side (using Angular) like this: $window.sessionStorage.setItem('loggedInUser', JSON.stringify(val)); For logout authentication on the backend (using Passportjs), I have ...

Can a single camera be utilized for capturing two different scenes?

Hey there! I'm currently working on rendering two different scenes with a camera that moves in sync between the two. Here's what I'm trying to accomplish: I need to display two separate point clouds in two distinct scenes, but I want the ca ...

Exporting CSS file from css-loader in Webpack: A step-by-step guide

My application structure is set up like this: /src /app.js /styles.css /images /img.png The content of the app.js file is as follows: const styles = require('./styles.css'); console.log(styles) // => I want a URL to t ...

Efficiently loading and locally filtering data in Angular 2 using Observables

In my Angular 2 application, I have successfully implemented an input with autocomplete that calls an API for server-side filtering and value retrieval. However, I am now facing a challenge as I need to add more inputs to my page that do not require server ...

The modal is nowhere to be found, only the backdrop is visible

Upon clicking the edit button in my HTML code, I expected a modal to appear but it did not pop up. <div class="modal fade" id="editModal"> <div class="modal-dialog" role="document"> <div class="modal-content"> &l ...

Is there a way to retrieve the original JSON string from a GWT JavaScriptObject?

Working with JSONP in my GWT application has presented some challenges. When the server sends a json string, I am able to retrieve it in the form of a JavaScriptObject on the client side. The issue arises when my json data contains complex structures, usi ...

Control the prompt with the Puppeteer typing function

Hello, I am currently attempting to log into a system that looks like the following: The input fields are labeled as username and password, with buttons labeled as login and cancel. I am trying to input data into these fields and click on the login ...

What is the method for specifying the type of a Custom Component in Typescript?

I have developed a custom React component called Title, which dynamically renders different HTML elements like h1, h2, h3, h4, h5, h6, span, or div based on the props provided to the component. Everything is working perfectly: No errors related to typescr ...

How can I delete the Location Box from Google Maps that appears in the top left corner?

My goal is to display all warehouse locations from Google Maps on my website by utilizing Google Map's iframe: <iframe src="http://maps.google.com/maps?q=118+Lamington+Rd.+–+Bateman+Student+Center,+Branchburg,+NJ+08876&amp;output=embed" fram ...

The prop "chartData" was invalid as the type check failed. It was expecting an Object but received Undefined

Just starting out in programming and encountering issues when trying to display a chart using dummy data. The specific error message is "Invalid prop: type check failed for prop 'chartData'. Expected Object, got Undefined". Essentially, I need to ...

Switch up the position of the background with onmouseover interactions

I'm currently seeking assistance with a problem I've encountered while attempting to change the backgroundPosition of a block element when a specific link from a list is hovered over. I am looking for a solution that can be implemented in an exte ...

Retrieving the value of a cell in a table row by clicking on a particular column

After clicking on a specific column in a table, I was able to retrieve all row values by using the event and accessing the value with event.currentTarget.cells[4].innerText();. However, I want this functionality to be triggered only when a certain column, ...