Utilize Vue.js - Link computed properties with data()

I am currently working on an input field that needs to be either blank or pre-populated based on certain conditions.

  • Condition A: If the user is a new student, the field should be blank
  • Condition B: If the user is an existing student, the field should be populated

The data for this input field is retrieved from either the data() function or a computed: property. Here is an example:

data () {
  return {
    studentName: '', // empty student name property (new student route)
    studentPersonality: ''
  }
},
computed: {
  ...mapGetters({
    getStudent // existing student object (edit student route)
  })
}

The input field should be blank if the user is arriving from the /new student route, or populated with existing student information if they're coming from the /edit route.

To populate the input field with the existing student's name, I can assign getStudent.name to v-model as shown below.

<input type="text" v-model="getStudent.name">

Alternatively, to clear the field, I can assign studentName to v-model

<input ... v-model="studentName">

Challenge: I am trying to use getStudent.name if it exists, and fallback to the blank studentName data() property if it does not. I have attempted:

<input ... v-model="getStudent.name || studentName">

This approach seemed to work initially, but it was deemed invalid and caused console errors

'v-model' directives require the attribute value which is valid as LHS

What am I missing or doing wrong?

Answer №1

Having the input field register to different properties in your vue component is not necessary.

If you want a computed property that is also settable, you can define it using a set & get method.

computed: {
  student_name: {
    get: function() {
      return this.$store.getters.get_student.name
    },
    set: function(val) {
      this.$store.commit('set_student_name');
    }
  }
}

Another approach is to separate the value from the input change handler in the input element itself, using the getter as you've set it:

<input type="text" :value="getStudent.name" @input="update_name($event.target.value)">


If you really need to use two different properties, you can set them on a created/activated hook:

created: function() {
  this.studentName = this.getStudent
},
activated: function() {
  this.studentName = this.getStudent
}

Remember to always delegate the update to the store, so either use the get/set computed property or the value/update separation.

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

Utilizing VueJS to transfer information for constructing a pricing plan chart

This is my first experience with VueJS, so I would greatly appreciate any advice or alternative methods to solve the issue. You can view my progress so far here. I am working on creating a pricing plan table where users can explore four different payment ...

Is there a way to incorporate external HTML files into my webpage?

Looking to update an existing project that currently uses iFrames for loading external HTML files, which in this case are actually part of the same project and not from external sites. However, I've heard that using iFrames for this purpose is general ...

AngularJS allows for the creation of cascading dropdown selects, where the options in the second select

I'm struggling to access the version data stored in the server model, but it's not cooperating. My suspicion is that when the page loads, the initial data from the first select isn't available yet because it hasn't technically been sel ...

Tips for revealing a link after the user clicks on the submit button

I am looking to set up a webpage that will display a hyperlink after the submit button is clicked. For example, 1) wedding 2) engagement 3) birthday All three items are checkbox buttons and there is a textbox to input the budget. After clicking the sub ...

Having issues with reading files in PHP using AJAX? Explore alternative methods for downloading files seamlessly

I need to store a value in a txt file and allow the user to download it. Currently, the value is successfully written to the txt file, but the readfile function does not execute, preventing the download from starting. The PHP code is on the same page as ...

Have the getter functions for reactive objects in Vue 3 been transformed into computed values?

Is the memoization of bookCount in this instance handled equivalently to a computed reference? const author = reactive({ name: 'John Doe', books: [ 'Vue 2 - Advanced Guide', 'Vue 3 - Basic Guide', 'Vue 4 - ...

VueJS can manipulate an inline template by dynamically changing its content and reinitializing

this particular query shares similarities with the discussions on VueJS re-compiling HTML in an inline-template component as well as How to implement Vue js directive in an appended html element Regrettably, the approach suggested in those threads is no l ...

Building a web proxy with node.js and express

I'm currently in the process of designing a personalized web proxy using JavaScript to allow users to surf the internet through a designated website, similar to this . One challenge I encountered is transferring the response from a URL back to the us ...

Using jQuery to crop an SVG view box

I'm currently working on a sticker website project for a client who requires the ability to crop an image within a specific SVG shape, resembling a Halloween face (shown below). The uploaded image should be displayed only within this shape while hidi ...

Retrieve the JSON response from the server and store it in variables using jQuery's AJAX function with the `done

I am trying to retrieve a JSON response from the server upon clicking a button and then parse it into a div. However, I am struggling with how to accomplish this. <button type="submit" id="btPay" name="btPay"> Go for Pay ...

Leverage the power of integrating Power BI with Javascript to easily retrieve an

I have embarked on a mission to integrate PowerBI into my web application. Below is the code snippet that I have implemented: window.config = { instance: 'https://login.microsoftonline.com/', tenant: 'common', //COMMON OR YOU ...

Transform the Standard class into a generic one in typescript

I've created a class that can take JSON objects and transform them into the desired class. Here's the code: import {plainToClass} from "class-transformer"; import UserDto from "../../auth/dto/user.dto"; class JsonConverter { ...

Using jQuery's setInterval to consistently refresh the value of a data attribute

I am struggling to dynamically update the data-left value of a div with the class name "tw_marquee_scroller" every 1 second. The intended behavior is for the value to increment by 10 each time, starting at 10 and increasing by 10 in subsequent seconds. H ...

Tips for incorporating error messages based on specific errors in HTML

In the current setup, a common error message is displayed for all errors. However, I want to customize the error messages based on the specific type of error. For example, if the password is invalid, it should display "invalid password", and for an invalid ...

Using PHP, create a redirect page that utilizes AJAX and jQuery for a seamless user experience

My goal is to navigate from page a to the profile page with a post session in between. Let's assume that the data is stored in a variable called $name as a string. The current code on page a looks like this: jQuery("#result").on("click",function(e){ ...

The 'substr' property is not found in the type 'string | string[]'

Recently, I had a JavaScript code that was working fine. Now, I'm in the process of converting it to TypeScript. var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; if (ip.substr(0, 7) == "::ffff ...

Iterate over JSON dates in JavaScript

Trying to utilize JavaScript in looping through a JSON file containing time periods (start date/time and end date/time) to determine if the current date/time falls within any of these periods. The provided code doesn't seem to be working as expected. ...

leveraging vue script setup via content delivery network

Is it possible to write a Composition API script setup using a CDN like this? <template> {{message}} </template> <script setup> message:"welcome"; </script> I have searched for a solution but found none. I have used ...

What is the process by which photoswipe applies styles to blur an image upon clicking the share button?

If you want to see an example, check out this link: http://codepen.io/dimsemenov/pen/gbadPv By clicking on the Share button, you'll notice that it blurs the image (and everything else). Despite inspecting it closely, I still can't seem to figu ...

How can I use jQuery to either display or hide the "#" value in a URL?

I have a question that I need help with. Let's say I have the following links: <a href="#test1"> Test </a> <a href="#test2"> Test 2 </a> When I click on Test, the URL will change to something like siteurl/#test1. However, whe ...