项目场景:
今天在回顾Vue基础的过程中,想用传统html和原生凭借着记忆尝试引入Vue并使用,然后发现自己真拉了。记忆不仅模糊,还混乱了,Vue2混着Vue3就在那瞎整!接下来看看是怎么报错的吧。
问题描述:
html结构如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
</head>
<body>
<div id="app"></div>
</body>
<script>
const app = Vue.createApp({
data() {
return {
message: '666'
}
},
template: "<h2>{{message}}</h2>"
})
app.mount("#app")
</script>
</html>
好家伙,666没渲染出来,直接咔咔给我报错。
Uncaught TypeError: Vue.createApp is not a function。
我还搁那纳闷,我想,不是createApp创建一个Vue应用,然后mount给节点挂载上去就行了吗?怎么Vue.createApp这方法还没了呢。
原因分析:
后来屁颠屁颠去看了文档,发现是自己记混了,Vue.createApp和mount这是Vue3的写法,然而我引入的是Vue2。
官网写的明明白白,Vue2用的是new,并且是el挂载节点。
Vue2写法如下:
var app = new Vue({
el: '#app',
data: {
message: '666',
},
template: '<h2>{{message}}</h2>',
});
下面这种是Vue3的写法
const app = Vue.createApp({
data() {
return {
message: '666'
}
},
template: "<h2>{{message}}</h2>"
})
app.mount("#app")