Transfer information from an HTML document to a Vue application that has been registered

I have a Vue application set up in the following manner:

import { createApp } from 'vue';
import RecommendedJobsWidget from './RecommendedJobsWidget.vue'

createApp(RecommendedJobsWidget).mount("#recommendedJobsWidgetInstance");

Here is how my HTML looks:

<body>
  <div id="recommendedJobsWidgetInstance">
    <recommended-jobs-widget :message="'messagehere'"></recommended-jobs-widget>
  </div>
<script src="/ui/migrate/dist/recommended_jobs_widget.js"></script>
</body>

Even though my app is loading correctly, I am experiencing issues with passing a prop named message to the <recommended-jobs-widget> component. I have defined the prop in my component like this:

props: ['message']

However, when I try to access the prop within my component, it seems to be unavailable. I have tried different solutions with no success in getting my data passed as a prop.

If anyone could offer any assistance, it would be greatly appreciated.

Answer №1

It was mentioned earlier by @AfterDark017 that Vue3 has a way of hiding data from itself using defineProps or useAttr. However, the data is still accessible in the main.ts script, which is crucial for mounting purposes.

One way to work around this in index.html is as follows:

<body>
  <div id="app" data-recaptcha-site-key="_NOT_REALLY_">
  </div>
  <script type="module" src="/src/main.ts"></script>
</body>

In main.ts

const recaptchaSiteKey = document
  .getElementById("app")!
  .getAttribute("data-recaptcha-site-key") as string;

createApp(App)
  .provide(RECAPTCHA_SITE_KEY, recaptchaSiteKey)
  .mount("#app");

To access the data, use inject like so:

import { inject } from 'vue';
const recapchaSiteKey = inject(RECAPTCHA_SITE_KEY);

Answer №2

From my understanding, passing data through props to root components in VueJS 3 is not supported.

When the root component is automatically rendered inside a mounted <div> container, it strips out any content within it. However, simply including the following code will still render the root component (unless there is no <template>):

<body>
  <div id="recommendedJobsWidgetInstance"></div>
  <script src="/ui/migrate/dist/recommended_jobs_widget.js"></script>
</body>

I also needed to pass data into Vue components, and the closest solution I found after extensive research is this: Pass data from html file into registered vue app

Although you cannot access it through props, you can retrieve the attribute value using Vanilla JS DOM methods like document.getElementById("app").getAttribute("someVariable")

In your specific case:

<body>
  <div id="recommendedJobsWidgetInstance" message="messagehere"></div>
  <script src="/ui/migrate/dist/recommended_jobs_widget.js"></script>
</body>

Then, within your RecommendedJobWidget.vue component:

<template>
  <div>
    <!-- your HTML -->
  </div>
</template>

<script>
export default {
  name: "RecommendedJobWidget",
  data() {
    return {
      message: ""
    }
  },
  mounted() {
      this.message = document.getElementById("recommendedJobsWidgetInstance").getAttribute("message");
  }
}
</script>

If there is a better approach, I'm eager to learn about it, as I find Vue3 to be primarily designed for SPAs.

Answer №3

My approach involves securely sending data using semantic methods, particularly utilizing meta tags. By embedding the data in the HTML render, it can be converted into meta tags instead of being passed as props. This enables the Vue app to retrieve the data after the head has loaded and dynamically render the component based on the head content. This strategy allows for a dynamic component loading approach within the main app. I plan to test this concept and will share my code soon.

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

Determine the exact beginning and ending positions of a word when dividing it using Javascript

After creating a special function that breaks down a word based on spaces while keeping punctuation marks intact, I was able to achieve the desired result. function tokenizeUtterance( utterance ) { let spilittedUserText = utterance.toString().match( /[& ...

How to access the api variable in JavaScript

When attempting to retrieve variables from an API object, I encountered the obstacle of them being nested inside another object named "0" in this particular case. Here is a screenshot from the console: enter image description here Below is the JavaScrip ...

How can I utilize React to pull information from the Google Taxonomy API?

Seeking assistance with React development, as I am a beginner and looking to retrieve data from this URL and organize it into a tree structure. I not only want to fetch the data but also display it in a tree format. My current code successfully retrieves t ...

Is there a way for me to retrieve the value nested within an object within another object from this Api response?

Hey there, I'm currently struggling to retrieve the value of faceit_elo from within the csgo object. I attempted using data.games.csgo.faceit_elo but unfortunately it didn't yield any results. Any suggestions on how to access this value would be ...

Exploring the benefits of event subscription nesting

One feature I'm currently utilizing is the Angular dragula drag and drop functionality, which enables me to effortlessly move around Bootstrap cards within the view. When an item is "dropped," it triggers the this.dragulaService.drop.subscribe() funct ...

The readyState of Ajax is consistently anything but 4

I have encountered an issue with my JavaScript code. I am running these codes in order to display data based on user input. Despite there being no error connection and the connection happening properly, whenever I enter a name it always goes into the else ...

The process of implementing server-side rendering for React Next applications with Material-ui using CSS

I have developed a basic React application using Next.js with an integrated express server: app.prepare() .then(() => { const server = express() server.get('/job/:id', (req, res) => { const actualPage = '/job' const ...

The prop observation was activated without any alterations

Within my component, I have a prop X that I assign to data Y during the created hook. This setup allows me to easily modify Y without affecting X. Both X and Y are Arrays. Additionally, I've set up a watch on prop X to ensure Y is updated whenever X ...

Is there a way to utilize nodemon without having to install it through npm?

I'm having trouble with my network not allowing me to use npm install. Is there another way for me to install and use nodemon? I've noticed that Node only runs after setting PATH variables on Windows. I attempted to set the path for nodemon, but ...

Switch between using the useState hook by toggling it with the MUI Switch

Looking to implement a custom Dark Mode feature for a specific element on my create-react-app website using MUI. I have successfully implemented the Switch to change the state on toggle, but I am having trouble figuring out how to toggle it back and fort ...

Error message: Cypress Vue component test fails due to the inability to import the Ref type (export named 'Ref' is missing)

Recently, I created a Cypress component test for my Vue component by mounting it and verifying its existence. The component utilizes Vue's Ref type and is structured as a TypeScript component. However, during the test execution, Cypress encountered a ...

JSON Nesting with Ember.js and Rails

I'm currently developing a simple Ember / Rails application that involves multiple nested relationships. For instance: class Release < ActiveRecord::Base has_many :tracks end Upon accessing my Releases endpoint, I receive JSON data in the follo ...

Encountering a "focus" error with React-Native-Phone-Input library, where the property is null

For my project, I decided to incorporate the react-native-phone-input library. Everything was going smoothly until I encountered an issue with their focus function. Initially, it worked perfectly fine, but subsequently, when I attempted to input a phone nu ...

Is it possible to extract a string from a file and import the extracted string into another file using require() in NODE.js?

My file structure looks like this: collegesapp ├── node_modules │ ├── express │ ├── connect │ ├── jade │ └── passport ├── routes │ └── routes.js ├── views │ ├── index.jade │ ...

I am interested in developing a JavaScript program that can calculate multiples of 0.10

I am looking to let users input values that are multiples of 0.10, such as - 0.10, 0.20, 0.30....1.00, 1.10, 1.20...1.90, and so on. When a user enters a value in the text box, I have been checking the following validation: amount % 0.10 == 0 Is this a ...

Develop a jQuery dialog box without assigning an ID

I need help with jQuery to create a dialog that opens and then populates with values. When I tried to create the dialog using jQuery, it kept using old values because the div already existed on the page. I want to create a new instance of the dialog usin ...

Encountered an issue running "npm install" within the Vue3 composition API

Encountering an error while trying to install dependencies in a Vue3 project. npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-c ...

Tips for incorporating the "build" directory into the Travis-CI build process and deployment of an npm module

Currently, I am working with a Typescript module that has a directory ./src And I also have travis-ci set up for the project. language: node_js node_js: - 5.1.0 install: - npm install - npm install -g mocha - npm install -g gulp - npm install -g tsd - ...

utilizing the data provided by a user in the "prompt" window within my HTML code

Looking to utilize user input from the prompt window. This is my custom JavaScript form: var answer; function load() { answer=prompt("what is your name?", "Write your name here"); return answer; } function hideNsee() { var HNS = docume ...

Random crashes are observed in Selenium tests during the execution of JavaScript code

Currently, I am in the process of writing functional tests for a Zend application. These tests are executed using PHPUnit and a wrapper called https://github.com/chibimagic/WebDriver-PHP In order to handle the extensive use of JavaScript and AJAX in the a ...