1、vue3组件支持多个根节点
//vue3开始页面
<template>
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
</template>
2、组合式API
options API ,如vue2所规范的
<template>
<div>
<div>
<button @click="changeBlue()">变蓝色</button>
<button @click="changeGreen()">变绿色</button>
</div>
<div class="con" :style="`color:${this.$data.color}`">改变区域</div>
</div>
</template>
<script>
export default {
name: "Content",
data() {
return { color: "yellow" };
},
methods: {
changeBlue() {
// console.log(this.$data.color);
this.$data.color = "blue"
},
changeGreen() {
// console.log(this.$data.color);
this.$data.color = "green"
},
},
};
</script>
<style>
.con {
width: 500px;
height: 300px;
border: 1px solid yellow;
}
</style>
composition API 是将管理一个功能的所有变量和方法放到一起
<template>
<div>
<button @click="changeBlue()">变蓝色</button>
<button @click="changeGreen()">变绿色</button>
</div>
<div class="con" :style="`color:${color}`">改变区域</div>
</template>
<script>
import { ref } from "vue";
export default {
name: "Content",
setup() {
const color = ref("yellow");
function changeBlue() {
console.log(this.color);
color.value = "blue";
}
function changeGreen() {
color.value = "green";
}
return {
color,
changeBlue,
changeGreen,
};
},
};
</script>
<style>
.con {
width: 500px;
height: 300px;
border: 1px solid yellow;
}
</style>
(1)选项式API和组合式API 两种风格是并存关系,不是非此即彼
(2)需要大量逻辑组合的场景,可以使用compition API进行增强
3、vue2和vue3双向数据绑定原理发生改变;
vue2的双向数据绑定是利用ES5的API Object.definePropert()对数据进行劫持,结合发布订阅模式的方式来实现。
vue3中使用了ES6的Proxy API对数据代理。
相比vue2,,西永proxy的优势如下:
- defineProperty只能监听某个属性,不能全对象监听
- 可以省去for in ,闭包等内容来提升效率(直接绑定整个对象即可)
- 可以监听数组,不用再去单独对数组做特异性操作vue3可以检测到数组内部数据的变化
4、vue2和vue3定义数据变量和方法的改变
在vue2中定义数据在data(){},创建方法在methods(){}。
在vue3中直接在setup(){}中,setup中定义的变量和方法最终都要在末班中只用,所以最后都得return
<script lang="ts">
import { defineComponent, ref } from 'vue';
export default defineComponent({
name: 'App',
setup() {
//使用ref,说明这个数组就是全局在面板中可以使用了
const girls = ref(['美女1','美女2','美女3'])
const selectGirl = ref('2')
//设置一个函数
const selectGirlFun = (index: number) => {
//改变selectGirl的值要加value
//要得到值要加value ,这些都因为使用了ref函数
selectGirl.value = girls.value[index]
}
//在标签中使用的变量要使用return
//为什么要使用return,因为有的不需要在标签中使用的就不用return
return{
girls,
selectGirl,
selectGirlFun
}
},
});
</script>
5、vue2和vue3声明周期钩子函数不同
-
vue2
中的生命周期beforeCreate
组件创建之前created
组件创建之后beforeMount
组价挂载到页面之前执行mounted
组件挂载到页面之后执行beforeUpdate
组件更新之前updated
组件更新之后- beforeDestory组件销毁前
- destory组件销毁后
-
vue3
中的生命周期setup
开始创建组件onBeforeMount
组价挂载到页面之前执行onMounted
组件挂载到页面之后执行onBeforeUpdate
组件更新之前onUpdated
组件更新之后
而且Vue3.x
生命周期在调用前需要先进行引入
import {
reactive,
toRefs,
onMounted,
onBeforeMount,
onBeforeUpdate,
onUpdated,
} from "vue";
Vue2--------------vue3
beforeCreate -> setup()
created -> setup()
beforeMount -> onBeforeMount
mounted -> onMounted
beforeUpdate -> onBeforeUpdate
updated -> onUpdated
beforeDestroy -> onBeforeUnmount
destroyed -> onUnmounted
activated -> onActivated
deactivated -> onDeactivated
errorCaptured -> onErrorCaptured
6、vue3加入了对TypeSrcipt的支持
文章用于学习与分享。欢迎指正。