Dynamic VueJS v-model binding target

We are currently in the process of designing a form with numerous dependencies that span across different levels of inputs. For example, if parent1.input1 = 'test', then child1.input1 should also be 'test'. However, if child1.input2 = 'more test', then child1.input3 should equal 'more test'.

let v = new Vue({
  el:'#someEl',
  data:{
    parentval1:'foo',
    parentVal2:'bar',
    children:[
      {childVal1:'bax', modelAttr:'parentVal1'},
      {childVal2:'bix', modelAttr:'childVal1'},
      {childVal3:'boom', modelAttr:'childVal2'}
    ]
  },
  methods:{
    whichModelField(modelAttr){
      swith (modelAttr){
        case 'parentVal1':
          return xx; //should be bound to some data property if modelAttr === 'parentVal1'
          case 'childVal1':
           return yy; //should be bound to some other data property if modelAttr === 'childVal1'
      }
    }
  }
})
<div>
  <p id='parent'>
    <input id="1" placeholder="test" v-model="parentVal1"/>
  </p>
  <p id='child1' v-for="child in children">
    <input  placeholder="test" v-model="whichModelField(child.modelAttr)"/>
    
  </p>
</div>

I have managed to dynamically bind the v-model attribute, but I am struggling to achieve true dynamism between the current item's context and the parent data context. In other words, I want to be able to bind to a data property at any level within the data object, and I can't seem to find the correct syntax to accomplish this.

Check out the jsfiddle here

Answer №1

In Vue, you are able to access properties using strings in JavaScript

let v = new Vue({
  el:'#someEl',
  data(){
    const self = this
    return {
    parentval1:'foo',
    parentVal2:'bar',
    children:[
      {childVal1:'bax', modelAttr:'parentVal1'},
      {childVal2:'bix', modelAttr:'childVal1'},
      {childVal3:'boom', modelAttr:'childVal2'}
    ],
    whichModelField: {
      get parentVal1(){
           return self.parentval1
      },
      set parentVal1(val){
           self.parentval1 = val
      },
      get childVal1(){
        return self.children[0]['childVal1']
      },
      set childVal1(val){
        self.children[0]['childVal1'] = val
      },
      get childVal2(){
        return self.children[1]['childVal2']
      },
      set childVal2(val){
        self.children[1]['childVal2'] = val
      }
      
    }}
  }
})
.as-console-wrapper {
  height: 0px !important
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="someEl">
  <p id='parent'>
    <input id="1" placeholder="test" v-model="whichModelField['parentVal1']"/>
  </p>
  <p id='child1' v-for="child in children">
    <input  :placeholder="child.modelAttr" v-model="whichModelField[child.modelAttr]"/>
    
  </p>
</div>

Answer №2

Here is the solution you are seeking:

new Vue({
    el:'#app',
    data:{
        parent:'',
        child:''
    },
    watch:{
        parent: function(value){this.child = value}
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <p id='parent'>
    <input id="1" placeholder="test" v-model='parent'/>
  </p>
  <p id='child1'>
    <input id="1" placeholder="test"  v-model='child' :value='parent'/>
    <!-- 1 and parent>input#1 should be bound to same value -->
    <input id="2" placeholder="more test" :value='child'/>
    <!-- 2 and 3 should be bound to same value -->
    <input id="3" placeholder="more test" :value='child'/>
  </p>
</div>

Answer №3

To ensure that 2-way binding only occurs between the parent and the first child in Vue, I intentionally separated them from the other children. This way, updates made by the children won't affect the parent component.

new Vue({
  el:'#app',
  data:{
    parent:'foo',
    child:'bar',
    children:[
      {placeHolder:'bax'},
      {placeHolder:'bix'},
      {placeHolder:'boom'}
    ]
  },
  watch:{
      parent: function(value){debugger; this.child = value}
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input id="1" v-model="parent" placeholder="test"/>
  <input v-model="child"
         :id="0"
         :placeholder="children[0].placeHolder" />

  <input  v-for="i in children.length - 1"
         :value="child"
         :id="i + 1"
         :placeholder="children[i].placePlaceholder" />
</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

What are your thoughts on using a click function within the same tag as an ngFor directive in Angular and JavaScript?

There is a table with a row element called tr. Should the `Click` event use the same tag as the `*ngFor` directive? If this is not recommended, how can I enhance the code? ...

Guide on Implementing Right-to-Left (RTL) Support in Material UI React

Currently, I am in the process of developing an application designed for LTR usage, but I am interested in adding RTL support as well. The application itself is built on top of Material UI React. By using CSS Flex Box, I have managed to rotate the applicat ...

Utilize Knockout.js to generate a table based on a Json response

I'm currently working on a project that involves creating a table using JSON response and Knockout.js. Here's how I've set it up: First, in my JavaScript file: $(document).ready(function() { $.ajax({ method : "POST", url ...

An error has been noticed: "Unexpected token o" - Syntax is not

I'm currently developing a web application and have encountered an issue: $("#post").click(function () { var u = $('#u').val(); var j = $('#j').val(); $.post("http://www.myweb.php", { u: u, j: ...

Ingress-nginx rewriting destination target

I have set up an nginx ingress for my front-end built in vuejs. apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: vuejs-ingress namespace: default annotations: cert-manager.io/cluster-issuer: letsencrypt-prod nginx.ingress.kubern ...

obtain access token using JavaScript

I am trying to obtain an access token using my refresh token in JavaScript. Here is the code snippet I am using: $.ajax({ type: "POST", contentType: "application/x-www-form-urlencoded", url: "https://accounts.google ...

Node.JS: Ensuring a process has completed before moving on

I recently started working with node.js and I have encountered a problem that I need help with. Here is the issue: I am calling the 'startProcess' function and I want to execute the 'downloadFiles' function, wait for it to complete and ...

Steps for showing personalized validation error messages in Angular 7

Is there a way to highlight the input field of a form with a red border and display the message Password is invalid when a user types in a password that does not match the set password? I have managed to see the red border indicating an error when I enter ...

The data display in MUI-Datatable is experiencing an issue where it is unable to read properties of undefined, specifically when trying to split the data

Whenever I include data within the MuiDatatable, it triggers this error: Cannot read properties of undefined (reading 'split') Is there a solution to this problem so that the data can be properly displayed? To demonstrate the issue, I have se ...

What is the method for selectively applying a "fade to black" mask to an input field?

For my current project, I need to incorporate a design feature where a "fade to black" mask gradually appears on the left side of an input field once the text content reaches the maximum visible width of the input box. The image below provides a visual re ...

There was an unexpected error in angular.js while trying to work on a calendar widget based on angular-ui-calendar. The error message indicated that the argument 'fn' was expected to be a function but instead received Moment

I came across a similar topic earlier on Stack Overflow, but unfortunately, the issue wasn't resolved. So, I've decided to revisit this question and address it myself this time. In my app.js file, which is where my main module for the app is ini ...

The error message "Cannot access 'id' property of undefined" is being displayed

I have a file named auth.js along with a middleware called fetchuser. The code provided below is causing an error that I cannot figure out. The error occurs during the process of sending a token to the user and verifying whether the user is logged in or n ...

Running a Node.js server on a public IP address while utilizing socket.io

Take a look at the server code snippet below: express = require('express'); app = express(); app.use('/', express.static(__dirname + '/')); http = require('http').Server(app); io = require('socket.io')(htt ...

In the event that the get request fails, go ahead and clear the

Currently facing an issue and seeking a solution: I have a game running that retrieves the state of the game periodically. However, if a user logs out, the game ends but continues to send put requests at the set interval. I am exploring options like setti ...

Showing pictures from a JSON source

I am currently facing an issue while trying to display the cover art along with the search results. There seems to be a problem in the img src tag that is preventing the app from loading properly. Interestingly, when I direct the img to data.tracks[i].albu ...

Blurry text and icons in Bootstrap 3

Does anyone else notice a strange display issue with Bootstrap 3 fonts and glyphicons? It seems like the bitmaps and fonts are appearing blurry on desktops when using Firefox and Chrome, but everything looks fine on mobile devices. I've attached an ex ...

Troubleshooting a React JS and material-ui issue

Having an issue with material-ui integration in reactjs. Attempting to render a FlatButton, but encountering the error message: TypeError: _context$muiTheme is undefined As a newcomer to reactjs, I'm unsure of where the problem lies. Below is my code ...

Double Marker Challenge in Brochure

I am currently using Leaflet in conjunction with VueJs. I have encountered an issue where a double marker is appearing at a specific location when I add a marker: The code responsible for this behavior is as follows: mounted() { this.map = L.ma ...

Listening for server updates with jQuery

I am currently working on a web application that communicates with a server for database updates. The issue I am facing is that the update process can vary greatly in time, ranging from milliseconds to tens of seconds for larger updates. I would like to im ...

Could implementing a click/keydown listener on each cell in a large React datagrid with thousands of cells impact performance?

Years ago, before the advent of React, I mastered linking events to tables by attaching the listener to the <tbody> and extracting the true source of the event from the event target. This method allowed for a single listener for the entire table, as ...