Assign the default value of a Vue prop to the options of its parent component

I have a child component that needs to accept a value given in the component's parent's $options object as a possible default value.

In the background, the component should be able to receive its data through a prop or from a configuration. However, there is existing code that expects the data to be passed as an option to the main Vue instance.

The new way of creating the Vue instance looks like this:

new Vue({
    el: '#app',
    render: h => h(MainComp, { 
        props: {
            document: 'data.json'
        }
    })
});

The component is designed to calculate the prop's value from a config file if it is not provided (or set it to a default value of null):

import Config from './config.js';
[...]    
props: {
    document: {
        default: Config.document || null
    },

This setup works well.

However, in the legacy code, the Vue instance used to be created like this:

new Vue({
    el: '#app',
    document: 'data.json',
    render: h => h(MainComp)
});

and the data was accessed in the data() function by using

this.$parent.$options['document']
.

My initial thought was to incorporate this same code into the new default:

default: this.$parent.$options['document'] || Config.document || null

but it turned out that it doesn't work, as the docs mention that "props are validated before a component instance is created, so instance properties [are not] available".

So I attempted to define my "special default" through the data() function like this:

data() {
    return {
        document: document || this.$parent.$options['document']
    };
},

Unfortunately, Vue rightly points out: "The data property "document" is already declared as a prop. Use prop default value instead."

How can I break free from this cycle?

Answer №1

You can try this method:

default: () => this.$parent.$options['document'] || Config.document || null

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

Tips for changing the page URL upon click in a Vue.js application

I am currently developing a post board application using Vue.js and I am facing an issue with redirecting the page when a user clicks on each post. To handle this, I have made use of vue-route and axios in my project. Here is a snippet from index.js, ex ...

Automatically sync textbox width with gridview dimensions

My goal is to dynamically resize a number of textboxes so that they match the width of my gridview's table headers. The gridview will always have the same number of columns, but their widths may vary. However, as shown in the image below, the width va ...

React JS does not allow TextField and Select to change

I am relatively new to full stack development and I am currently working on a project to enhance my understanding of frontend development with React JS. While working on this project, I have been using Redux without any issues so far. However, I am facing ...

Encountering difficulties with managing the submit button within a ReactJS form

As I work on creating a User registration form using React JS, I encounter an issue where the console does not log "Hello World" after clicking the submit button. Despite defining the fields, validations, and the submit handler, the functionality seems to ...

Error message: The module '@project-serum/anchor' does not export the object 'AnchorProvider' as intended

I encountered an issue while attempting to run my react application. The issue: Attempted import error: 'AnchorProvider' is not exported from '@project-serum/anchor'. The import declaration in my code: import idl from './idl.json ...

Build a new shop using a section of data from a JSON database

Let's say I have a JSON store that is set up as shown below var subAccountStore = new Ext.data.JsonStore({ autoLoad: true, proxy: { type:'ajax', url : '/opUI/json/subaccount.action?name="ABC"' }, fields: ['acc ...

Having trouble resolving the dependency tree within react-navigation-stack

Trying to understand navigation in React-native and attempting to execute the following code: import React, {Component} from 'react'; import {StyleSheet, Text, View} from 'react-native'; import {createAppContainer} from 'react-nav ...

Incorporate External Web Page Information by Clicking a Button

Apologies if this question has already been asked, but despite my efforts to explore the available resources, I have not found a solution to my issue. I currently have an input field where users can enter their website, keyword, or industry. When they cli ...

AngularJS $http.get request not working as expected

Hi there, I'm currently facing an issue with retrieving data from a webpage for use on my own website. I'm working with AngularJS and attempting to fetch data from . When checking my page in Chrome, I encountered the following error: Refere ...

Why won't my controller function fire with ng-click in AngularJS?

I'm having trouble getting a function to execute when my button is clicked. Despite the fact that this code appears correct, the function defined in my controller isn't being triggered. The code compiles without errors as shown in the console. A ...

Showing AngularJS information on Views

After successfully implementing static HTML with views, as shown in this example: https://embed.plnkr.co/MJYSP01mz5hMZHlNo2HC/ I am now facing a challenge with integrating the angular-ui accordion within ng-view. You can view the accordion I am attemptin ...

Changing a transparent div with overlays into a visual representation of its underlying background

I am curious to know if it is feasible to carry out the operation mentioned, given that JavaScript doesn't currently have access to the contents of certain objects, such as a Flash video player. I have explored various screenshot plugins, but none of ...

The HTML page is failing to call the function in the JavaScript application

I recently started taking a YouTube Javascript course on chapter 34 titled "Make start button work" Javascript tutorial My HTML, CSS, and Javascript files are all located in the same folder. I am using VS Code along with the Live Server extension for codi ...

Retrieving the chosen value when there is a change in the select tag

Building a shop and almost done, but struggling with allowing customers to change product quantities in the cart and update prices dynamically. I've created a select-tag with 10 options for choosing quantities. I'd like users to be able to click ...

Rearrange the sequence of numbers using JQuery when an HTML element is deleted

I'm currently working on a simple functionality where I have 5 rows, each with its own number. So initially, the rows are numbered from 5 to 1. If I remove a value like 3, the sequence should adjust to 4, 2, 1, indicating that I now have only 4 rows ...

Need to capture click events on an HTML element? Here's how!

I am attempting to capture click events on an <object/> element that is embedding a Flash file This is the approach I have taken so far: <div class="myban" data-go="http://google.com"> <object class="myban" data="index.swf>">< ...

Leveraging the power of CSS calc() in combination with TailwindCSS styles and JavaScript

Can you explain why applying styles with TailwindCSS v3 to calculations using JS variables does not work? I'm working on a project using VueJS, and I've noticed that styling works fine when using calc as a string like this: ... <div class=&qu ...

Step-by-step guide on inserting a variable into .doc() to create a new table

Recently, I created a SignIn page that uses variables to store data fetched with document.getElementByClassName. Now, I am facing an issue while trying to create a new document on Firebase using the person's name stored in a variable. Struggling with ...

Ways to update a div periodically with new data fetched from a file - Here's How!

I am looking to auto-refresh a specific div every few seconds on my index.php page below. <?php session_start(); if (! check_write()) { redirect('testlogin.php'); return; } if (file_exists('lmt.json')) { $lmt = json_de ...

Abbreviating Column Labels in Google Visualization

Is there a way to use the google visualization API to display column headers in an abbreviated form in a table, but show the full labels in a pie chart using the same dataset? Check out this snippet of JavaScript: //create the dashboard and table chart ...