What is the best way to transfer a JavaScript object to a VueJS component?

Even though it may seem like a basic question, I'm having trouble figuring out how to accomplish this in VueJS

Here's the code I have in HTML:

<script>
 var config = {'cols':4,'color':'red'}
</script>

<div id="app">
   <mycomponent :config="config"></mycomponent>
</div>

var app = new Vue({
   el: '#app',
   data: {
      // config: config // I do not want to pass this
   }
})

Here's the scenario:

  • I am aware that it is not working because the config variable in the component is expecting app.config
  • I prefer not to pass it as data{ config:config } in the Vue Object.
  • One option could be to pass it as
    <mycomponent :config="{'cols':4,'color':'red'}"></mycomponent>
    , but the config will be lengthy and that is my last resort.
  • Additionally, the config remains constant once the page loads, so there's no need to bind values dynamically.

Is there a solution for this dilemma?

Answer №1

To enhance Vue's functionality, you have the option to include a global member directly within Vue itself. Update: Osuwariboy pointed out in the feedback that Vue is not able to recognize itself by name in the un-minified version of Vue. To work around this, it is necessary to create a data item for Vue as demonstrated below.

var app = new Vue({
   el: '#app',
   data: {
      Vue
   },
   components: {
      myComponent: {
        template: '<div>{{config}}</div>',
        props: ['config']
      }
   }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.min.js"></script>
<script>
 Vue.$config = {'cols':4,'color':'red'}
</script>

<div id="app">
   <my-component :config="Vue.$config"></my-component>
</div>

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

Is it possible that Typescript does not use type-guard to check for undefined when verifying the truthiness of a variable?

class Base {} function log(arg: number) { console.log(arg); } function fn<T extends typeof Base>( instance: Partial<InstanceType<T>>, key: keyof InstanceType<T>, ) { const val = instance[key]; if (val) { ...

The class name remains unchanged despite the change in value

I am currently working on a webpage that features two interactive tabs. The goal is to have one tab highlighted as "active" while the other remains inactive when clicked, and then switch roles when the other tab is selected. Below is the code snippet I ha ...

What is the process for incorporating custom translations into my Vuetify 2.x web application?

I'm diving into my first web app development using vuetify 2.x and vue-i18n. However, I'm encountering some challenges with implementing i18n for my own translations. Within my menu, I have the following entry: <v-menu bottom left offse ...

Focusing on pinpointing certain mistakes within Drupal 7

When working with Drupal, encountering errors is a common issue. While some errors are simple to fix, others can be quite complex and require significant time and effort to resolve, even if the website appears to function normally despite the error. My qu ...

The jQuery extension for XDomainRequest in the $.ajax function called onprogress is

Summary: I am trying to make this compatible with this: Detailed Explanation: My goal is to develop a jQuery extension that introduces a progress method to the $.ajax object and works seamlessly with IE8 & IE9's XDomainRequest object. Currently, I ...

Validating date parameter in Wiremock request - How to ensure dynamic date matching during testing?

Looking for some assistance in verifying that the date in a request is exactly Today. I've tried various methods from the documentation, but haven't achieved the desired outcome yet. Calling out to any helpful souls who can guide a junior QA thro ...

What is the correct method for downloading an Excel file in a Vue.js application?

I am having difficulty downloading an Excel file in xlsx format using my Vue.js application. The Vue.js application sends a post request to the Node.js application which then downloads the Excel file from a remote SFTP server. The backend application is fu ...

Generate a revised object from a function and return it to the caller

What is the most efficient way to update and return a new object from a function? I came up with this function: export const addItemToCart = (currentCart, item) => { const { name, ...otherProps } = item; // if the item is already in the cart if ...

Enhance and Modify feature using Javascript

I'm facing two issues with my product information form. Firstly, after I submit the data, I want the input fields to be cleared automatically. Secondly, the edit function doesn't seem to work at all. I'm quite stuck on how to resolve these p ...

Manipulate md-select options with Angular using setValue

My goal is to update a select option, but I'm having trouble getting it to work properly. When I use this.eventForm.controls.venue.setValue(event.venue.name);, the value of venue changes to match event.venue.name. However, the select option itself doe ...

Utilize CamelCase in jQuery for Better Code Readability

Upon examining the jQuery source code, I noticed an interesting use of camelcase: camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); } // where: rmsPrefix = /^-ms-/, rdashAlpha = /-([\da- ...

Elegant Box 2 - Ascending to the top when clicked

I am excited to share that I am using FancyBox for the first time in my project. This time, I decided to separate the image from the link for a unique user experience. The hover effect works perfectly fine - the issue arises when the link is clicked and th ...

Is it possible for the useUser() function within the Auth0 nextjs-auth0 library to retrieve user information without relying on cookie data?

The useUser() method by Auth0 is designed to retrieve information about a logged-in user by calling the /api/auth/me endpoint. This triggers the handleAuth() function, which sets up Auth0 (creating a sessionCache instance, etc.) and calls profileHandler(re ...

Is there a way to access the body html element within a template in vue.js?

I'm struggling to add styles to the body element of my HTML page. It seems like I can't access it directly from the template because there's another body element nested inside the main body. Even when I try to change the style using JavaScri ...

FullCalendar fails to load in Bootstrap 4 tab

My current project involves utilizing Bootstrap 4 tabs, and I encountered an issue with displaying a FullCalendar on the second tab. Specifically, I am using version 5.2.0 of the FullCalendar library. While the calendar functions correctly when placed on t ...

next-images encountered an error during parsing: Unexpected character ''

Having trouble loading images dynamically with next-images: //Working <Image src={require(`../../images/exampleImage.jpg` )}/> However, I want to use a dynamic URL like this: //Not working <img src={require(`../../images/${image}.jpg` )}/> Th ...

Retrieve information from a controller and pass it to a Component in AngularJs

Having an issue with passing data from a controller to a component in AngularJs. The data is successfully passed to the template component, but it shows up as undefined in the controller! See below for my code snippets. The controller angular.module(&a ...

Unlocking the Power of Marionette.CompositeView: Passing Parameters to Marionette.ItemView

Is there a way to access the app.vent from Marionette.ItemView? One solution might be to pass a parameter (app.vent) to Marionette.ItemView from Marionette.CompositeView. Here's the code snippet: // view/compositeView.js define([ 'marionet ...

Fetching data from a server using Angular and displaying it in controllers

I am currently working on a project where I need to retrieve JSON files and their content using a factory in AngularJS. My main goal is to make this data accessible to other controllers, but I am struggling with getting the factory to return the deityData. ...

Puppeteer experiencing issues with missing relative modules and dependencies not being found

After installing puppeteer via npm, I encountered errors when trying to compile it: This dependency was not found: * ws in ./node_modules/puppeteer/lib/WebSocketTransport.js To resolve this, you can run: npm install --save ws These relative modules we ...