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

JavaScript practice causing browser to crash

I've been troubleshooting this code line by line in the console, and everything seems to be working fine. However, when I input consecutive even numbers, my browser freezes. The solution is probably right in front of me, but I just can't figure i ...

Understanding the functionality of app.listen() and app.get() in the context of Express and Hapi

What is the best way to use only native modules in Node.js to recreate functionalities similar to app.listen() and app.get() using http module with a constructor? var app = function(opts) { this.token= opts.token } app.prototype.get = function(call ...

"Help! I'm facing an issue with my PHP PDO insert statement

I've been working on developing a web application that allows users to create new projects, but I've hit a roadblock. For the past couple of days, I've been stuck on a particular issue related to the "New Project" button. When this button i ...

Managing values in Vue using v-model can sometimes lead to inconsistencies in value increment

When I try to increment or decrement the counter, my input shows a different value than what is in this.count. For example, when I increment the value, the input shows '3' but this.count === 2. Vue.component('product-item', { data: func ...

Creating a test environment for a Vue.js-electron application that incorporates Vuex

I need help setting up a Component and running a basic unit test on it. (I'm new to Vue.js and unsure of what information is necessary to solve my issue. Please let me know if you need additional code snippets to assist me.) user-information.vue: & ...

Dealing with redirect issues in a React-Material menu: A guide to troubleshooting and

When working with my menu, I face a variety of issues. First and foremost, within the initial RETURN section, there is a TREEITEM with a LISTITEM and a LISTITETEXT. I have included an OnClick event in the LISTITETEXT so that if the menu's id matches ...

Preventing Columns in SlickGrid from Being Reordered

Is there a way to prevent specific columns in SlickGrid from being reordered? I have tried looking for a solution but couldn't find one. Unlike the 'resizable' option, there doesn't seem to be an option for each column to allow or disal ...

Having difficulty displaying Laravel API data with Relationship in Vue Js

Working on a project that involves Laravel 10 API and Vue.js 3 frontend In my EmployeeController.php file, I have three models: Employee, Title, and Salary. The Employee model has a many-to-many relationship with the Salary and Title models, while the Sal ...

Trouble connecting JavaScript to Node application for proper functionality

After setting up Node/Express/EJS, I am now trying to include js files, but my alert("working"); is not working as expected. Quite ironic, isn't it? The main objective is to load learnJs.js in the browser and trigger the alert so that I can confirm e ...

Tips for including an external .js file in a .php file

In an attempt to call a JavaScript function located in an external file, I am facing some issues. Here is my folder structure: C:\xampp\htdocs\test\index.php C:\xampp\htdocs\test\js\functions.js index.php &l ...

Is there a way to dim and deactivate a button after it has been clicked once?

Hello, I am attempting to disable and grey out a button after it has been clicked once in order to prevent the user from clicking it again until they refresh the page. I hope my question is clear enough and that you can understand me. Below is the HTML cod ...

jQuery parent() Function Explained

checkout this code snippet - https://jsfiddle.net/johndoe1994/xtu09zz9/ Let me explain the functionality of the code The code contains two containers: .first and .second. The .first container has two default divs with a class of .item. The .second contai ...

Firebase and Angular 7 encountered a CORS policy block while trying to access an image from the origin

I am attempting to convert images that are stored in Firebase storage into base64 strings in order to use them in offline mode with my Angular 7/Ionic 4 application! (I am using AngularFire2) However, I encountered an error message stating: Access to i ...

Issue with displaying current date and time dynamically (JavaScript/JQuery)

In order to create a real-time chat using websockets, I want to show the time of a message posted in this format: "% sec/min/hour/day now". After conducting some research, I came across two functions that I have modified : // Get the TimeStamp va ...

What steps can be taken to resolve the error "Incompatible types: TodoItem undefined cannot be assigned to type TodoItem"?

I am currently in the process of learning TypeScript. Here is what's inside todoItem.ts: export class TodoItem { constructor( public id: number, public task: string, public complete: boolean = false ) {} printDetails(): void { ...

The link does not respond to the first click

I'm having an issue with the search feature on my website. The page includes an auto-focused text input element. As the user types, an ajax request is made and JQuery fills a div with search results. Each result is represented by an <li> elemen ...

Enhancing HTML "range" element with mouse scroll functionality for incrementing values in step increments

I'm working on developing a scroll feature that operates independently from the main window's scrolling function. I aim to trigger specific events in the primary window based on interactions with this separate scrollbar. The only solution I coul ...

Issues Arise when Attempting to Upload Files to AWS S3 Using Node.js as

Utilizing this AWS S3 NPM Package for managing S3 uploads from my Express server has presented me with a puzzling situation. The uploader fails to trigger the end function. var key = utils.createID(Date.now()); var s3 = require('s3'); var client ...

Encoding URLs for LoopBack applications

I am experiencing an issue with the filter I have: { "fields": {"goal":true,"amountPledged": true,"title": true},"where": {"title": {"like":`%${this.state.searchText}%`}} } The this.state.searchText value is bio. According to my understanding, it should ...

What is the best way to access the original observed node using MutationObserver when the subtree option is set to

Is there a way to access the original target node when using MutationObserver with options set to childList: true and subtree: true? According to the documentation on MDN, the target node changes to the mutated node during callbacks, but I want to always ...