简体   繁体   English

如何在新的 Vue3 项目中使用 Vue2 旧组件(.vue 文件)?

[英]How can I use Vue2 old component (.vue file) with a new Vue3 project?

Vue3 version is out, but I don't see any example of using old components code with the new version. Vue3 版本已出,但我没有看到任何将旧组件代码用于新版本的示例。 How come?怎么来的?

Here is my index.html:这是我的 index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Vue 3 Example using Vue 2 component</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="app">
      <h1>{{ product }}</h1>    
      <my-old-vue-component :my-prop="'my string in here'"></my-old-vue-component>
    </div>

      <script src="./main.js"></script>
      <script src="./myOldVueComponent.vue"></script>

    <!-- Mount App -->
    <script>
      const mountedApp = app.mount('#app')
    </script>
  </body>
</html>

Here is my main.js:这是我的 main.js:

const app = Vue.createApp({
  data() {
      return {
          product: 'my product',
      }
  }
})

Here is my old simple Vue2 component (myOldVueComponent.vue):这是我旧的简单 Vue2 组件 (myOldVueComponent.vue):

<template>

    <div>
        {{myProp}}
    </div>

</template>

<script>

  
    export default {
        name: "myOldVueComponent",
        props: {
            myProp: { type: String }
        },
        data() {
            return {
               
        },
       
    }

</script>

I'm getting error on the import of ".vue" file: uncaught SyntaxError: Unexpected token '<' (meaning the <template> tag inside my old component.我在导入“.vue”文件时遇到错误:uncaught SyntaxError: Unexpected token '<' (意思是我的旧组件中的<template>标签。

Vue2 components works in Vue3. Vue2 组件适用于 Vue3。 That is not the issue in your code.这不是您代码中的问题。


The problem is here:问题在这里:

<script src="./myOldVueComponent.vue"></script>

You can't import .vue files directly in a browser.您不能直接在浏览器中导入 .vue 文件。 You could not do it in vue 1,2 and you can't yet in vue 3. The browser is not able to understand that syntax, there needs to be a bundler that converts your code is something that can be used by the browser.你不能在 vue 1,2 中做到这一点,你不能在 vue 3 中做到。浏览器无法理解这种语法,需要有一个打包器来转换你的代码,以便浏览器可以使用。 The most popular bundlers are webpack, rollup ecc ecc最受欢迎的打包工具是 webpack、rollup ecc ecc

See: https://v3.vuejs.org/guide/single-file-component.html#for-users-new-to-module-build-systems-in-javascript请参阅: https : //v3.vuejs.org/guide/single-file-component.html#for-users-new-to-module-build-systems-in-javascript

I highly recommend using the Vue cli to setup your project, especially if you are a beginner to the npm/bundlers world我强烈建议使用Vue cli来设置你的项目,特别是如果你是 npm/bundlers 世界的初学者

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM