问题描述
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
我强烈建议使用Vue cli来设置您的项目,特别是如果您是npm / bundlers世界的初学者