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

问题描述

Vue3版本已经发布,但是我看不到在新版本中使用旧组件代码的任何示例。怎么会来?

这是我的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>

这是我的main.js:

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

这是我以前的简单Vue2组件(myOldVueComponent.vue):

<template>

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

</template>

<script>

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

</script>

导入“ .vue”文件时出现错误: 未捕获的SyntaxError: 意外的令牌“ (这意味着我的旧组件中的<template>标签。

解决方法

Vue2组件可在Vue3中使用。这不是代码中的问题。


问题在这里:

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

您不能直接在浏览器中导入.vue文件。您无法在vue 1,2中执行此操作,而在vue 3中仍无法执行。浏览器无法理解该语法,因此需要一个捆绑程序来转换您的代码,浏览器可以使用该捆绑程序。最受欢迎的捆绑包是webpack,汇总ecc ecc

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

我强烈建议使用Vue cli来设置您的项目,特别是如果您是npm / bundlers世界的初学者

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...