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

Tips on implementing a function within a navigation bar from a specific context

While working with a user authenticated context, I encountered an issue with the logout function. My goal is to have a link in the navigation bar that triggers the logout function and redirects me to the home page. However, I'm receiving a Typerror: l ...

Error in Next.js 13 due to Prisma table mapping causing hydration issues

I recently created a basic project in Next.js 13 and encountered a Hydration Error even though my project is not doing much. The code snippet below seems to be the cause of the issue: import { PrismaClient } from "@prisma/client"; export default ...

By pressing the "showMore" button, the page dynamically pulls in a json list from a file

Currently, my focus is on a dropwizard-Java project. My task involves retrieving and showcasing the first 10 items from a json list in a mustache view. If the user clicks on the "show more" link, I should retrieve the next 10 elements from the list and d ...

vuejs Creating a model for a list of radio items

Is there a way to define a v-model for a framework7-vue radio list item element? Checkboxes & Radios Vue Component <f7-list-item radio name="my-radio" v-model="method.val" value="ISNA" title="Islamic Society of North Ame ...

Is it recommended to utilize addEventListener?

Is it better to use the addEventListener method in these scenarios? <input id="input" type="file" onchange="fun()> or document.getElementById("input").addEventListener("change", function() { fun(); }); What are the advantages of using one over ...

Clicking on a href link inside a scrollable div-container causes it to malfunction, causing the page to jump

I have a draggable div container that contains dynamically generated content. In order to display this container, I use the following code: $( function() { $( "#dialog-message" ).dialog({ modal: true, height: 400, buttons: { Fertig: functi ...

Steps to configure JavaScript to initially conceal a div within a continuous loop

I have implemented a JavaScript function to toggle the show/hide functionality of a div class. The content of the div and the button that triggers the toggle action are both inside a while loop. Initially, I used "div id" in my JavaScript code, but it was ...

Guide on modifying values using both input fields and buttons at the same time

I am facing an issue with my input field that is designed to accept numbers. I want the value to be changed both via keyboard input and buttons. The buttons are functioning correctly unless I try to use keyboard input as well. For instance, if I enter 10 ...

The information returned to the callback function in Angular comes back null

In my Node.js application, I have set up an endpoint like this: usersRoute.get('/get', function(req, res) { //If no date was passed in - just use today's date var date = req.query.date || dateFormat(new Date(), 'yyyy-mm-dd&ap ...

JQuery - Select element by clicking outside

I'm trying to figure out how to hide an element when clicking outside of it. Found a solution at: https://css-tricks.com/dangers-stopping-event-propagation/ $(document).on('click', function(event) { if (!$(event.target).closest('#m ...

sending numerous ajax requests and they all seem to be returning identical results

When firing multiple ajax requests using the setinterval() function, I noticed that both requests are bringing back the same information from another page. Here is the JavaScript code: function views() { setInterval(function(){var xmllhttp //alert ...

The error message "The useRef React Hook cannot be invoked within a callback function" is displayed

I'm currently working on developing a scroll-to feature in Reactjs. My goal is to dynamically generate referenced IDs for various sections based on the elements within an array called 'labels'. import { useRef } from 'react'; cons ...

Guide to extracting a key from a specific index within JSON using Google Apps Script

Is there a way to extract values key11-key44? Just managed to retrieve values key1-key4: const data = JSON.parse(UrlFetchApp.fetch(url, options); const keys = Object.keys(data.paths); for (let a in keys) {return keys[a]} { "id": &q ...

Deactivate the checkboxes with varying attributes

My goal is to disable checkboxes with different warehouse locations once a warehouse is selected. For instance, if I select California, I want all checkboxes from other states to be disabled. This should be based on the whseID attribute, but I am strugglin ...

Setting the 'redirect_uri' for Identity Server 4 in a React JS application and directing it to a specific view using a route

After following the instructions at , I attempted to login to Identity Server from my ReactJS application. Upon successful login, http://localhost:3000/callback.html was loaded with id_token and access_token in the URL. However, I noticed that this callbac ...

Exploring the significance of a super in Object-Oriented Programming within JavaScript

During my studies of OOP in JS, I encountered the super() method which serves to call the constructor of the parent class. It made me ponder - why is it necessary to invoke the parent class constructor? What significance does it hold for us? ...

What is the Best Way to Toggle the Visibility of Specific Buttons in a Table Using Jquery?

<html> <head> <script> $( "#clickMeButton" ).click(function() { $(this).next("#hiddenButton").slideToggle( "slow", function() { // Animation complete. }); }); </script> </head> <body> <table> <tr& ...

Creating a Webgrid in MVC and integrating it with a custom class in AngularJS

Hey there, I'm a beginner when it comes to AngularJS and I'm looking to bind the webgrid within the method of AngularJS. $scope.SaveDetails = function () { debugger; var UserID = '@Session["ID"]'; ...

Use a for loop to fill an array with values and then showcase its contents

I have been trying to figure out how to populate an array and display it immediately when targeting the route in my NodeJS project. Currently, I am able to console log a list of objects. However, I want to populate an array and show it when accessing loca ...

The browser is preventing a cross origin request in Fetch

Currently, I am utilizing node, express, and react to build a sign-in portal. In the frontend, I have created app.js and signin.js files. The partial code snippet in the signin.js file looks like this: onSubmitSignIn = () => { fetch("http://localhost:3 ...