1.双向数据绑定原理不同
(1)vue2:vue2的双向绑定原理是利用了ES5的一个API Object.defineProperty对数据进行劫持,结合发布订阅模式的方式来实现的。
(2)vue3:vue3中使用了ES6的proxy API对数据进行代理。
补充:vue3的proxy的优点:
2.API不同
(1)vue2使用的是选项类型API,在代码里分割了不同的属性,比如data、methods、computed等。
<template>
<div>
<h2>{{ message }}</h2>
<button @click="increaseCounter">Increase</button>
</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello Vue!',
counter: 0
}
},
methods: {
increaseCounter() {
this.counter++
}
}
}
</script>
(2)vue3使用的是组合式API,相比于vue2更加的灵活和可复用,在setup里使用ref
函数来创建可响应式的数据,并使用普通JavaScript函数来管理组件的逻辑。
<template>
<div>
<h2>{{ message }}</h2>
<button @click="increaseCounter">Increase</button>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const message = ref('Hello Vue!')
const counter = ref(0)
function increaseCounter() {
counter.value++
}
return {
message,
counter,
increaseCounter
}
}
}
</script>
3.生命周期钩子不同
(1)vue2的生命周期钩子
- beforeCreate 组件创建之前
- created 组件创建之后
- beforeMount 组价挂载到页面之前执行
- mounted 组件挂载到页面之后执行
- beforeUpdate 组件更新之前
- updated 组件更新之后
- beforeDestory 组件销毁之前
- destoryed 组件销毁之后
(2)vue3的生命周期钩子:
- setup 开始创建组件
- onBeforeMount 组价挂载到页面之前执行
- onMounted 组件挂载到页面之后执行
- onBeforeUpdate 组件更新之前
- onUpdated 组件更新之后
- onBeforeUnmount() 组件销毁之前
- onUnmounted() 组件销毁之后
而且vue3.x 生命周期在调用前需要先进行引入。
(4)定义数据变量和方法不同
vue2:vue2是把数据放入data中,在vue2中定义数据变量是data(){} ,创建的方法要在methods:{} 中。
vue3:,vue3就需要使用一个新的setup()方法,此方法在组件初始化构造的时候触发。使用以下三个步骤来建立反应性数据:
- 从vue引入reactive;
- 使用reactive() 方法来声明数据为响应性数据;
- 使用setup()方法来返回我们的响应性数据,从而template可以获取这些响应性数据。