Correct way to import a script / module / component into a page in Nuxt?

自闭症网瘾萝莉.ら 提交于 2021-02-11 13:59:51

问题


I'm new to js, vue & nuxt so quite confused about what is the correct and best way to import a script / module / component into an HTML page and run it.

For example, I know that this works with an event listener in the js script:

<template>
<div>
<button id="importJS">Go!</button>
</div>
<template>

<script src="~/index.js"></script>

But is something like this better?:

@import "~/index.js"

<template>
<div>
<button id="importJS">Go!</button>
</div>
<template>

And / or should only the main function be exported as a module / component something like this?:

module.exports = JSexport;

With then an import like this?:

<JSexport />

Or like this?:

<JSexport></JSexport>

In summary, my question is what is the canonical way and why is that the case?

Many thanks!


回答1:


Its pretty simple. If you create an page or an component then you have got an structure like this:

You alwas go following:

1. Template
2. Script
3. style


<template>
   <div class="some_div"> {{ page_name }} </div>
</template>

<script>
export default {
   data(){
      return {
         page_name: "test page"
      }
   }
}
</script>

<style>
.some_div {
   width: 100%;
   height: 100px;
   background: green;
}
</style>

To import some other component or script you will need to use import inside the script tags

<script>
import someScript from "from/some/path/script.js";
import someComponent from "@/components/someComponent.vue;
export default {
   data(){
      return {
         page_name: "test page"
      }
   },
   components: {
      someComponent // dont forget to register your component after you import it
   }
}
</script>

After this you can use ur component / script inside your page/component what else. After you have registered your imported component you can use it inside your HTML markup:

<template>
   <div class="some_div"> 
      {{ page_name }}
      <someComponent></someComponent>
   </div>
</template>



回答2:


I'm fall in love with vue for their documentation, the official page is awesome.

You can find all official answers to your questions in the Vue Style guide. It has a lot of examples about what is good or bad to do:



来源:https://stackoverflow.com/questions/61249944/correct-way-to-import-a-script-module-component-into-a-page-in-nuxt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!