如何在新的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中也做不到。浏览器无法理解该语法,需要有一个bundler来转换您的代码。这是浏览器可以使用的东西。最受欢迎的捆绑器是webpack、roll-up-ecc-ecc-

请参阅:https://v3.vuejs.org/guide/single-file-component.html#for-新使用javascript 模块构建系统的用户

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

最新更新