How can default props be set for a nested object in Vue?

Here's how I've defined my props:

myHouse = {
  kitchen:{
    sink: ''
  }
}

I attempted to set the default props like this, but it didn't work as expected.

props: {
    house: {
        type: Object,
        default: () => {
            kitchen : {
                sink: ''
            }
        }
    }
},

Any guidance on correctly setting default props for an object like this?

Answer №1

According to the documentation:

When setting defaults for objects or arrays, a factory function must be used.

The issue lies in not returning the default object. To address this, you have two options:

props: {
    house: {
        type: Object,
        default: () => ({ // Ensure to include parentheses
            kitchen : {
                sink: ''
            }
        }) // Make sure to return the object here as well
    }
},

Alternatively, you can do:

props: {
    house: {
        type: Object,
        default: () => {
           return  {
              kitchen : { // Remember to include 'return'
                sink: ''
              }
           } 
        }
    }
},

Answer №2

Here is a possible solution:

  props: {
   house: {
       type: Object,
        default: () => ({
          kitchen: {
             sink:''
            }
       })
  },
 }

For a working example, you can check this codesandbox

If the previous solution does not work for you, another option is to use a normalized computed property:

     props: {
         house: { type: Object }
       },
    computed: {
           normalizedHouse() {
              return {
                      kitchen:{
                         sink: ''
                        }
                     }
            }
         }

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

Disabling CSS transitions and attempting to alter the style of an HTML element using JavaScript may not consistently work as expected

Currently, I am in the process of creating an animated effect for a website that involves moving two elements' positions over time and resetting them to their original position. Only one element is displayed at a time, and the animation should run smo ...

What is the best way to eliminate a vertical line from the canvas in react-chartjs-2?

Can someone please lend me a hand? I've been working on a project in React JS that involves using react-chartjs-2 to display charts. I'm trying to incorporate a range slider for the chart to manipulate values on the x-axis, as well as two vertic ...

fetching indexeddb information using the equivalent of a "WHERE IN (a,b)" query

I've been working on transitioning from websql to indexeddb, but I'm struggling to recreate the SELECT query: "SELECT * FROM tableA WHERE cid ='"+cid+"' AND hid IN("+hid+",1) ORDER BY hid DESC LIMIT 1"; function getMyData(e) { var ...

Creating a Loop with v-for in Laravel Framework that works similarly to the Forelse in Laravel

Trying to achieve a similar functionality to forelse in Laravel framework blade using Vue. This is just a test to check if a table has records or not, and if not, display a default value: <tr> <td colspan="4">There's No Records Yet< ...

Having trouble getting Calendly Webhooks to function in a node.js environment with ngrok?

Hello everyone, this is my first time seeking help on Stack Overflow so please bear with me if there are any flaws in my question. I recently started using the Calendly Teams version and decided to implement the Webhooks feature on a Node.js web applicati ...

The alternating colors in the sorting table are not visible due to the divs being hidden with the display set

I've come across a problem that has me stumped. So, there are two sorting filters on a table and one of them hides rows that don't apply, messing up the alternating colors. Take a look at the function that sorts and the CSS below. The issue is pr ...

What methods can be used to customize the font and background color of a website for different user groups?

Trying to incorporate a template into my project. My client has requested the following: The regular user area should feature a blue background. The professional user area should have an orange background. Is there a way to set up a condition to change ...

Strategies for resolving the module not found error: Unable to locate '@mui/icons-material/Adb'?

I installed material-ui core using the command below: npm i @material-ui/core However, when running my reactjs code afterwards, I encountered this error message: Module not found: Can't resolve '@mui/icons-material/Adb' Can someone pleas ...

Unable to associate ngModel because it is not recognized as a valid property of the "Component"

Currently, I am in the process of creating a custom form component using Angular 4. I have included all necessary components for ngModel to function properly, but unfortunately, it is not working as expected. Below is an example of my child component: ex ...

Enhanced JavaScript Regex for date and time matching with specific keywords, focusing on identifying days with missing first digit

I have a specific regular expression that I am using: https://regex101.com/r/fBq3Es/1 (audiência|sessão virtual)(?:.(?!audiência|sessão virtual|até))*([1-2][0-9]|3[0-1]|0?[1-9])\s*de\s*([^\s]+)\s*de\s*((19|20)?\d\d) ...

Troubleshooting Bootstrap 3.0: Issues with nav-tabs not toggling

I have set up my navigation tabs using Bootstrap 3 in the following way: <ul class="nav nav-tabs pull-right projects" role="tablist" style="margin-top:20px;"> <li class="active"><a role="tab" data-toggle="tab" href="#progress">In Pr ...

Implementing pagination for images offers a user-friendly browsing experience

My friend and I are in the process of creating a website that displays images from two directories in chronological order. The image name serves as a timestamp, and we generate a JSON object using PHP with the code below: <?php $files = array(); $dir ...

The MUI select box stays fixed in its position relative to both the height and width of the viewport while scrolling

Whenever I click on the MUI select, the dropdown box stays fixed in the viewport both horizontally and vertically as I scroll. Ideally, it should move along with the select. Any ideas on how to fix this issue? I attempted adjusting the positioning of the ...

Utilizing Ajax to send a parameter to a separate PHP script

I have a dilemma that I need help with. Currently, I have a table displaying data using PHP and SQL in the following format: What I want to achieve is to be able to click a button, retrieve the ID value, and based on that, execute another SQL query to dis ...

Using the v-for directive to create sequential lists

I am struggling to display pairs of data from an object based on category using nested v-for loops. The object, categoryArray, contains entries such as {stage 1, red}, {stage 1, blue}, {stage 2, orange}, {stage 3, brown}, {stage 2, green. My desired displ ...

Sending POST Requests with Node and ExpressJS in the User Interface

Just diving into the world of Node.js and Express.js, I'm attempting to create a form submission to an Express.js backend. Below is a snippet of the code I am working with: var author = 'JAck'; var post = 'Hello World'; var body ...

Require assistance with handling Ajax when a function with an Ajax call is repeatedly invoked

I am seeking guidance with ajax as I am still new to it. A problem arises when the same ajax call is made multiple times before the previous one completes its execution, resulting in an empty pop-up on the user interface. How can this issue be resolved? Es ...

Retrieving the data from an Angular website using a curl command

Currently, I am facing an issue with my Angular 2 application running on Google Earth. The problem arises as Google Earth uses an outdated version of Chrome that is not compatible with Angular 2. To tackle this obstacle, I need to find a way to initiate th ...

Internal server error encountered while making an AJAX call using AngularJS routing

I'm currently diving into AngularJS with a basic application focused on customers and their orders. The issue I'm encountering involves a table that showcases the list of customers along with a link to access their respective orders. However, upo ...

Oh no, there seems to be an issue with accessing the 'map' property in REACT JS. It appears to

Upon attempting to delete an item, I encountered an error message stating "cannot read notes, property of undefined". Despite this issue, the map function seems to be functioning as expected. It is my belief that there may be an error within the filter fun ...