Creating Dynamic Input Binding in Vue.js with an Array of Computed Properties

Currently, I am faced with a situation where I need the v-model binding of an input field to be determined by the computed property's returned value.

Take a look at the example provided below:

<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b1d0a18ca8e929c83908988">[email protected]</a>/dist/vue.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />  
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div id="app">
    {{value}}
    <input type="text" v-model="myName.first">
    <input type="text" v-model="myName.second">
</div>
  <script>  
    new Vue({
        el:'#app',
        data:{
            value:{
                first: '',
                second: ''
            }
        },
        computed: {
            myName: {
                get(){
                    return {first:'this.value.first',second:'this.value.second'};  //this will actually come from an API
                },
                set(newValue){
                    this.value.first = newValue.second;
                    this.value.second = newValue.second;
                }
            } 
        }     
    });
  </script>
</body>
</html>

In the code snippet above, I aim to bind the first field to value.first and the second field to value.second based on the values returned from the computed property. Currently, there are only two returned values - value.first and value.second. However, in reality, this will depend on logic.

I suspect that I may not be utilizing the get and set methods correctly. Any assistance would be greatly appreciated.

Please note: In a previous inquiry along similar lines, there was only one value returned in the computed property instead of an array/object. The solution provided worked well. However, this time, we have two values that require setting. You can refer to that thread here: Vuejs Input Binding Based on Computed Property

Answer №1

Instead of using data or set/get, you have the option to directly connect v-model to a computed property.

CodePen

<input type="text" v-model="myName.first">

data:{},
computed: {
   myName: function() {
       return this.$store.state.myName; //or whatever your api is
   } 
}     

Ensure that the value of your computed property is available before the input component is rendered.

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

Issues with refreshing Datatables functionality

I’ve hit a roadblock while troubleshooting this issue, and it’s gotten quite frustrating. That's why I've turned to Stackoverflow for help once again. As a beginner, I ask for your patience and thank you in advance for any assistance. In my ...

What is the reason behind the success of this location?

Curious about the functionality of this particular JavaScript code with its corresponding HTML structure: function getCityChoice() { const location = document.querySelector("form").location.value; console.log(location) } <form name="reserve" a ...

Is it possible to maintain the sidebar while eliminating the scrolling JavaScript?

Looking to recreate the image display style on Facebook where pictures appear in a lightbox format. The challenge I'm facing is figuring out how they manage to have the sidebar with no visible scroll bar inside... If you want to see this for yourself ...

Retrieve data from backend table only once within the bootstrap modal

How can I retrieve values from a table once a modal is displayed with a form? I am currently unable to access the values from the table behind the modal. Are there any specific rules to follow? What mistake am I making? I would like to extract the values ...

Execute the identical script in NPM, but with various parameters each time

Recently, I created a nodeJS script with a parameter. Currently, using npm start allows me to pass arguments and run my script successfully. However, I'm now faced with the challenge of passing multiple arguments to npm start in order to run multipl ...

Tips for activating autocomplete / IntelliSence for sass within vue documents on VS Code platform?

Despite using lang="sass" in my .vue files within VS Code, I am experiencing issues with the autocomplete feature for CSS properties. (Vetur is already installed on my system) Is there anyone who can provide a solution or suggest settings that need to be ...

Utilizing JSON Data with JQuery: A Beginner's Guide

I am using a setTimeout function to reload another function every 5 seconds. The update_list function is responsible for rendering entrances in a view. However, when there are many entrances and you have scrolled down, the list empties and reloads every e ...

What is the best way to create a "tile-based board" for this game?

I am working on a project to create a board made up of tiles, but I am facing difficulty in filling up the entire board area. Currently, I have only managed to create 1 column of the board, as shown in the image. Can someone guide me on how to fill the ent ...

Having trouble with the line graph in Flot when a threshold is applied?

I'm currently working on a website where I am incorporating flot for data visualization. However, I'm facing an issue with setting a threshold on my line graph. Instead of coloring the data differently, it seems to be separating it at the thresho ...

What is the method for setting a default image to be preloaded in filepond?

Currently, I am working on a Laravel view for editing a record which includes an associated image. My goal is to have the image preloaded inside the input file so that when you submit the form, the same image is sent or you can choose to change it. // Con ...

Instructions on how to retrieve a JSON file from an external source

I'm experiencing difficulties in downloading a json file from an external URL using nodejs. The issue arises when the downloaded file (dumpFile.json) is created empty. var file = fs.createWriteStream("download/dumpFile.json"); let URL = 'http:// ...

What could be the reason for the sudden lack of content from the Blogger API?

For weeks, I've been using the Google API to retrieve JSON data from my Blogger account and showcase and style blog posts on my personal website. Everything was functioning flawlessly until yesterday when, out of the blue, the content section stopped ...

What are some methods to prevent cookies from being overridden?

Just beginning my journey in web development. Currently utilizing asp.net Web API and Angular with token authentication. Every time a user logs in, I set the token in a cookie and send it with each request. Everything has been running smoothly so far, bu ...

Utilizing a Grunt task to inject code into an AngularJS file

Hey there! I'm currently looking for a way to add some code into my app.js file that will only execute when I run the "grunt serve" task. This code is just two lines of javascript that should be present when I test the app on my local environment. Unf ...

When using AngularJS, the templateUrl feature delays the initialization of the controller, causing issues with dependent code

Recently, I began experimenting with AngularJS and so far, everything seems to be going smoothly except for one small issue. Let's consider a scenario where I have two directives, with one directive relying on the other, like this: angular.module(&ap ...

Error Occurs While Getting Request Parameters with Ajax Post and Express.js

When utilizing ajax to send data from a JavaScript frontend to an Express.js backend server, I am having trouble retrieving the posted data in the API method of my express.js. Below is the code where I attempt to parse the request data. Your assistance i ...

Looking to trigger the closing of a q-popup-proxy by clicking a button from a separate component

I am currently working with a q-popup-proxy component in my project. <q-btn label="Add Fault" class="addFaultButton" dense @click="openPopUp()"> <q-popup-proxy position="center" v-if="openFaults" ...

Encountering an npm error: How can I install compiler-sfc that satisfies the peer dependency requirement for @babel/core?

Review of my packageJSON "devDependencies": { "@fortawesome/fontawesome-svg-core": "^1.2.35", "@fortawesome/free-solid-svg-icons": "^5.15.3", "@vue/compiler-sfc": "^3. ...

The secure exchange of HTTP-only cookies between a REST API developed with Spring Boot and a frontend application

Currently, I am in the process of integrating a Spring Boot API with VueJS. Initially, everything was functioning smoothly when I stored the JWT in localstorage. However, numerous online resources suggest that it is advisable to refrain from storing the J ...

The client is not displaying any events on the full calendar

I am currently working on creating a unique calendar display that showcases all the weekdays and events, regardless of the specific day in a month. The dates extracted from the database may seem "random", but in my C# code, I have devised a method to map e ...