What is the best way to access a variable from a .js file?

Is there a way to access a variable defined in a JavaScript file from a Vue file and pass it to the Vue file? In the following code snippet, there is a template.js file and a contact.vue file. The template file converts MJML to HTML and saves the output to a variable called plainHtml. How can this variable be accessed in the Vue file?

template.js

const mjml2html = require('mjml')
const Vue = require('vue')

const app = new Vue({
    data: {
        name: ''
    },
    template: `
<mj-section>
  <mj-column>
    <mj-text font-size="20px" color="#F45E43" font-family="helvetica">Hello {{ name }}</mj-text>
  </mj-column>
</mj-section>`
})

const renderer = require('vue-server-renderer').createRenderer({
    template: `
<mjml>
  <mj-body>
    <!--vue-ssr-outlet-->
  </mj-body>
</mjml>`
})

renderer.renderToString(app).then(html => {
    const htmlWithoutDataServerRenderedAttribute = html.replace(`data-server-rendered="true"`, '')
    const plainHtml = mjml2html(htmlWithoutDataServerRenderedAttribute)
    console.log(plainHtml.html)
})

contact.vue

<template>
   <div class="sign_up" id="signupform">
     <main role="main">
      <div class="SignUp_container">
      <form class="form-signup" @submit.prevent="processForm">
      <input type="text" name="name" placeholder="Enter First Name" required/>
      <input type="text" name="lname" placeholder="Enter Last Name" required/>
      <input type="email" name="mailaddr" placeholder="Your email address" required/>
      <div class="sign_cancel_buttons">
      <router-link to="/">
        <button id="canlbtn" type="cancel" class="clbtn">
          Cancel
        </button>
         </router-link> 
        <button id="signupbtn" type="submit" name="sendmsg-button" class="signbtn">
          Sign Up
        </button>
      </div>
      </form>
      </div>
     </main>
   </div>
</template>
<script>
   export default {
       methods: {
       
       // How can I access the `plainHtml` variable here?
       
       }
   }
</script>

Answer №1

To start, open the file template.js and define a variable to store the final result of converting your HTML code. Once you have defined the variable, add the following line to the end of the file:

export { varHTML }

Next, in contact.vue, you will need to import and use the export from template.js. Keep in mind that you may need to adjust the import path based on your specific file structure:

import { varHTML } from './template.js'
<script>
   export default {
       data() {
         return {
           plainHtml: null
         }
       },
       methods: {
         // How can I access plainHtml here?
       
         // Any method that requires plainHtml can now be implemented
       },
       created () {
         this.plainHtml = varHTML
       }
   }
 </script>

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

What is the mechanism behind angular2's spa routing functioning seamlessly without the need for the hash character in the url?

During my experience with the Angular2 "Tour of Heroes" tutorial, I made an interesting observation about how their single page application router functions without a trailing hash symbol (#) in the URL. This differs from the Kendo SPA router, which typica ...

What is the optimal method for transmitting data for a substantially large music playlist via HTTP?

I am currently in the process of developing an online music player. My main challenge lies in retrieving a comprehensive list of songs from the database and transmitting it to the user. The user should have the ability to create playlists on-the-go, hence ...

CRITICAL ERROR: CALL_AND_RETRY_LAST Unable to allocate memory - JavaScript heap exhausted while in production mode

Last week in production, I kept encountering a persistent issue: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory. Despite attempting to increase the HEAP size, my efforts were ineffective. Since this problem is affecting ...

What are some solutions for troubleshooting a laptop freeze when running JavaScript yarn tests?

Running the yarn test command results in all 20 CPU cores being fully occupied by Node.js, causing my laptop to freeze up. This issue is particularly troubling as many NodeJS/Electron apps such as Skype, MS Teams, and Slack are killed by the operating syst ...

Ensure that the central section of the slider remains illuminated

Looking for help with customizing my "product" slider, lightSlider. I want the middle div to always be highlighted when navigating through the slider. Here's what it looks like currently: Link to screenshot - current. My goal is to achieve this look: ...

Every time I attempt to launch my Discord bot, I encounter an error message stating "ReferenceError: client is not defined." This issue is preventing my bot from starting up successfully

My setup includes the following code: const fs = require('fs'); client.commands = a new Discord Collection(); const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js')); for(const file of com ...

Transforming Ember's ajax query string

Using ember-model, I am making a request like this: App.Video.find({'sort':'createdAt+asc'}); to retrieve a sorted list of videos. This should result in the following request: http://localhost:1337/api/v1/videos?sort=createdAt+asc How ...

Can you provide the function that updates subscription and account details using Recurly JS?

Recurly has unfortunately declined to provide assistance with this issue. I must understand the specific format of the objects, as Recurly will not process any extra data or incorrect query arguments (which vary for each function). Ruby: subscription = ...

Transform a list of file directories into a JSON format using ReactJS

I am developing a function that can convert a list of paths into an object structure as illustrated below; this script will generate the desired output. Expected Output data = [ { "type": "folder", "name": "dir1& ...

Is it considered secure to use v-html to display text content?

When working with Laravel/Blade apps, I often use Purifier to ensure that the output text is safe: {!! Purifier::clean($pageContent->content) !!} Now I'm curious if there are any similar tools available in Vue.js 3 to safely output content like th ...

Introducing Laravel 6's Hidden Gems: Unleash the Power of @push

Hey everyone, I'm a newcomer to the world of Laravel and currently using Laravel 6.0 I've encountered an issue with my javascript code that utilizes @push. Strangely enough, the script only functions properly when I manually insert the code into ...

Changing date and time into milliseconds within AngularJS

Today's date is: var timeFormat = 'dd MMM, yyyy hh:mm:ss a'; var todayDate = dateFormat(new Date(), timeFormat); Can we convert today's date to milliseconds using AngularJS? Alternatively, how can we use the JavaScript function getT ...

Grunt Pokes at XML to Set a Variable Destination Name

When using grunt-xmlpoke to update an XML file, the path of the XML file is provided as a parameter. The issue arises when the first WebConfigPath (key) in the files section is interpreted as a string. This results in updating a local copy of the XML fil ...

retrieve the current image source URL using JavaScript

In the template below, I am looking to extract the current img src URL and utilize it in a fancybox button. For example, in the template provided, there are 3 images from https://farm6.staticflickr.com. When clicking on these images, the fancybox will ope ...

What is the best way to incorporate animation using Tailwind CSS within my Next.js project?

I have a challenge with placing three images in a circular path one after the other using Tailwind CSS for styling. I've identified the circular path and keyframe style for the images. How do I configure this style in my Tailwind config file and imple ...

Storing various data entries within a MySQL database through the use of Vuex

I am currently facing an issue with inserting multiple data into my database using Vuex. Despite only inserting two data points, I keep getting the error message: COLUMN DOESN'T MATCH VALUE COUNT AT ROW 1. https://i.stack.imgur.com/qBcvK.png Below i ...

Display the content of a Vue file directly on the webpage

I am currently developing a website to showcase UI components using plain CSS. The project is built with Vue, utilizing standard HTML and CSS. One of the key features I am working on is providing users with two views for each component: 'Preview' ...

Is there a way to find the JavaScript Window ID for my current window in order to utilize it with the select_window() function in

I'm currently attempting to choose a recently opened window while utilizing Selenium, and the select_window() method necessitates its WindowID. Although I have explored using the window's title as recommended by other sources, and enabled Seleni ...

Webpack dynamically imports files from a folder

In order to streamline my development process, I have a specific structure for organizing React components. Each main component has its own components folder right alongside it. Currently, I find myself manually importing each component from the components ...

Is it possible to import Vue directly from the "/path/to/vue.js" file without using npm or NodeJs?

Is it possible to build a web app using just a single index.js file and importing other available files like shown in this image: https://i.stack.imgur.com/02aFF.png encountering the error message: import not found: default Do you have to use Vuejs wit ...