如何从.js文件中检索变量?

时间:2020-11-09 18:20:56

标签: javascript vue.js

如何从Vue文件访问js文件中定义的变量?有没有办法将此变量传递给vue文件?在下面的代码中,我有一个template.js文件和一个contact.vue文件。我正在将模板文件中的mjml转换为html,我需要访问从vue文件保存到plainHmtl变量中的输出。

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 do I access plainHtml here?
       
       }
   }
</script>

1 个答案:

答案 0 :(得分:1)

在template.js中,定义一个变量,您将在其中获得转换html的最终结果,将其定义后,只需将其添加到文件末尾即可。

export { varHTML }

现在在contact.vue中,您必须导入并使用从template.js进行的导出,请考虑必须根据处理文件的情况来修改导入路径:

import { varHTML } from './template.js'
<script>
   export default {
       data() {
         return {
           plainHtml: null
         }
       }
       methods: {
         // how do I access plainHtml here?
       
         // any method that is going to be needed now will have plainHtml available
       },
       created () {
         this.plainHtml = varHTML
       }
   }
 </script>