Why is it that when accessing the property of an object within a computed object, it returns as undefined instead of the object itself? Which method would be more suitable in this

Salutations.

To provide some context, my intention in posing this query is to dynamically render a child component within a form based on the selection made using the <app-selector> Vue component, as straightforward as that.

To simplify matters, I have included a snippet below to showcase the issue I am trying to resolve. Essentially, I aim to determine how the computed property cardTypeComponent functions. However, I am struggling to understand why the first return (return this.form) returns the object (this.form) with the desired property (card_type), while the second return (

return this.form.card_type ? this.form.card_type + 'Compose' : ''
) provides an empty string, suggesting that this.form.card_type is undefined even though it seems clear from the first return that it is not treated as such.

There is more complexity involved, including a server-side validation process after selecting an option before populating the value inside the this.form object. Additionally, the form interaction occurs in steps, so the component is only rendered after the user selects an option and clicks a button to access the corresponding form fields linked to that card type, rather than being immediately displayed upon selection as shown in the snippet. However, delving into these details may complicate the main question at hand. Thank you in advance.

Please refer to the Fiddle link provided below.

Snippet

var appSelector = Vue.component('app-selector', {
  name: 'AppSelector',
  template: `<div>
               <label for="card_type">Card Type:</label>
               <select :name="name" value="" @change="sendSelectedValue">
                 <option v-for="option in options" :value="option.value">
                  {{ option.name }}
                 </option>
           </select>
             </div>`,
  props: {
    name: {
      required: false,
      type: String,
    },
    options: {
      required: false,
      type: Array,
    }
  },
  methods: {
    sendSelectedValue: function(ev) {
      this.$emit('selected', ev.target.value, this.name)
    }
  }
});

var guessByImageCompose = Vue.component({
  name: 'GuessByImageComponse',
  template: `<p>Guess By Image Compose Form</p>`
});

var guessByQuoteCompose = Vue.component({
  name: 'GuessByQuoteComponse',
  template: `<p>Guess By Quote Compose Form</p>`
});

new Vue({
  el: '#app',
  components: {
    appSelector: appSelector,
    guessByImageCompose: guessByImageCompose,
    guessByQuoteCompose: guessByQuoteCompose,
  },
  data() {
    return {
      form: {},
      card_types: [
        {
          name: 'Guess By Quote',
          value: 'GuessByQuote'
        },
        {
          name: 'Guess By Image',
          value: 'GuessByImage'
        }
      ],
    }
  },
  computed: {
    cardTypeComponent: function() {
        return this.form; // return { card_type: "GuessByImage" || "GuessByQuote" }
        return this.form.card_type ? this.form.card_type + 'Compose' : ''; // return empty string ("") Why?
    }
  },
  methods: {
    setCardType: function(selectedValue, field) {
      this.form[field] = selectedValue;
      console.log(this.form.card_type); // GuessByImage || GuessByQuote
      console.log(this.cardTypeComponent); // empty string ("") Why?
    }
  },
  mounted() {
    console.log(this.cardTypeComponent); // empty string ("")
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <form action="#" method="post">
    <app-selector
      :name="'card_type'" 
      :options="card_types"
      @selected="setCardType"
    >
    </app-selector>
    {{ cardTypeComponent }} <!-- Always empty string !-->
    <component v-if="cardTypeComponent !== ''" :is="cardTypeComponent">
      
    </component>
  </form>
</div>

https://jsfiddle.net/k7gnouty/2/

Answer №1

Make sure to initialize this.form before setting a property on it in data. Vue's change detection caveat may cause issues otherwise. Consider using Vue.set when modifying the object:

methods: {
  setCardType: function(selectedValue, field) {
    Vue.set(this.form, field, selectedValue);
  }
}

If needed, declare the properties beforehand for better performance.

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

The communication between the extension and chrome.runtime.connect() fails, possibly due to an issue with the chrome manifest version

I've been working on converting a Chrome extension that stopped functioning in manifest version 2. I've removed inline JavaScript and switched from chrome.extension.connect to chrome.runtime.connect. However, I'm still encountering issues wi ...

How is it possible that this event listener is able to capture an event that was already sent before it was

I am facing an issue with my Vue JS code. When I click on the account <a> tag, it triggers the toggle method. The toggle method adds an event listener to the document. However, as soon as the toggle method is executed, the event listener fires and ...

Employing JavaScript for fading divs in and out sequentially

Hey there! I'm currently struggling with implementing transitions for my tool tips. Any assistance would be greatly appreciated! I am looking to have my "fader" divs fade in and out on click of a button, with each transition lasting 5 seconds. It&apo ...

Iterate over asynchronous calls

I am currently working with a code snippet that loops through an Object: for(var x in block){ sendTextMessage(block[x].text, sender, function(callback){ //increment for? }) } During each iteration, I need to make a request (send a Faceboo ...

Storing a class method in a variable: A guide for JavaScript developers

I am currently working with a mysql connection object called db. db comes equipped with a useful method called query which can be used to execute sql statements For example: db.query('SELECT * FROM user',[], callback) To prevent having to type ...

The animation in Material UI does not smoothly transition with the webkit scrollbar

I've been experimenting with CSS animations in Material UI's sx property to achieve a webkit scrollbar that eases in and out. However, instead of the desired effect, the scrollbar appears and disappears instantly. Whether I define the keyframes ...

Setting `tabBarVisible` to false does not function properly within a stackNavigation nested element

Details on my project dependencies: "react-navigation": "^3.6.0", "expo": "^32.0.0" I'm working with a TabNavigator that contains redirections to child components, which are StackNavigators. However, I'm facing an issue where I am unable to hide ...

Steps for checking if the specified row has been accurately filled out in a loop

Here is an example of how my JSON data is structured: { "main_object": { "id": "5", "getExerciseTitle": "TestFor", "language": "nl_NL", "application": "lettergrepen", "main_object": { "title": "TestFor", "language": "nl_NL", "exercises": [ { ...

Improving the pagination performance in AngularJS

I created an HTML template to showcase member details, along with adding pagination functionality to improve initial load time. Currently, I retrieve 15 members from the server at once and display them, allowing users to navigate through more members using ...

JQuery isn't functioning properly on dynamically generated divs from JavaScript

I'm currently tackling an assignment as part of my learning journey with The Odin Project. You can check it out here: Despite creating the divs using JavaScript or jQuery as specified in the project requirements, I am unable to get jQuery's .hov ...

Drop-down Navigation in HTML and CSS is a popular way to create

My navigation menu is functioning well and has an appealing design. The HTML structure for the menu is as follows: <div id="menubar"> <div id="welcome"> <h1><a href="#">Cedars Hair <span>Academy</span></ ...

Navigating the screen reader with the cursor位

Site Design Challenge I recently discovered that the master/detail design of my website is not very accessible. The main view features a column chart where each column represents a different month. Clicking on one of these columns reveals details in a nes ...

There was a mistake: _v.context.$implicit.toggle cannot be used as a function

Exploring a basic recursive Treeview feature in angular4 with the code provided below. However, encountering an error when trying to expand the child view using toggle(). Encountering this exception error: ERROR TypeError: _v.context.$implicit.toggle i ...

How can I display a Skeleton when pressing pagination buttons and then turn it off after 3 seconds?

Here is a snippet of my code featuring the use of a Skeleton as a placeholder for CardMedia: {loading ? ( <Skeleton variant="rectangular" width={308} height={420} animation="wave" /> ) : ( <CardMedia s ...

Transferring multiple data between PHP and JavaScript

Here is the code I am using for the on change event: <script> $('.BIR').change(function() { var id = $(this).val(); //get the current value's option $.ajax({ type:'POST', dataType: "json", ...

What is the best way to access the element menu with element-ui?

I am looking for a way to programmatically open an element in my menu, but I haven't been able to find any information on how to do it. HTML <script src="//unpkg.com/vue/dist/vue.js"></script> <script src="//unpkg.com/<a hr ...

What is the most effective way to eliminate error messages from the email format checker code?

Recently, I've been working on a code to validate forms using javascript/jquery. One particular issue I encountered was related to checking email format. The problem arose when entering an invalid email - the error message would display correctly. How ...

Having difficulty accessing the Material UI Icons

I encountered an issue when attempting to utilize Material UI icons - as soon as I added the icon component, an error occurred. https://i.stack.imgur.com/issmm.png For reference, you can find the code on CodeSandbox at the following link: https://codesand ...

Can I change the name of an item in ngRepeat?

When repeating in a view: ng-repeat="item in list" In some scenarios, the 'item' looks like this: { "name": "john", "id": 1 } While in others, it appears as: { "value": { "name": "john", "id": 1 } } Is there a way to rena ...

Learn how to extract data from the "this" object in JavaScript

Can anyone help me with retrieving the numbers generated by this code snippet? $("#100wattaren") .countdown("2018/01/01", function(event) { $(this).text( event.strftime('%D days %H hours %M minutes %S seconds') ); }); When I con ...