简介
Vue 3 在 2022 年 2 月 7 日成为新的默认版本。
Vue3优点:
- 性能提升,运行速度事vue2.x的1.5倍左右
- 体积更小,按需编译体积比vue2.x要更小
- 类型推断,更好的支持Ts(typescript)这个也是趋势
- 高级给予,暴露了更底层的API和提供更先进的内置组件
- 组合API (composition api) ,能够更好的组织逻辑,封装逻辑,复用逻辑
创建项目
1. 使用vite创建
vite是一个更加轻量(热更新速度快,打包构建速度快)的vue项目脚手架工具。
vite官方文档:https://cn.vitejs.dev/
创建项目 npm init vite-app
项目名称 或者 yarn create vite-app
项目名称
启动项目 npm run dev
或者 yarn dev
2. 使用 vue-cli 创建
npm install -g @vue/cli # 或 yarn global add @vue/cli
vue create hello-vue3
创建vue(3)实例
1. 在main.js中导入createApp函数
2. 定义App.vue组件,导入main.js
3. 使用createApp函数基于App.vue组件创建应用实例
4. 挂载至index.html的#app容器
import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
createApp(App).mount('#app')
新的组合API
vue3生命周期钩子函数
setup
创建实例前onBeforeMount
挂载DOM前onMounted
挂载DOM后onBeforeUpdate
更新组件前onUpdated
更新组件后onBeforeUnmount
卸载销毁前onUnmounted
卸载销毁后
vue2 —> vue3
beforeCreate -> 使用 setup()
created -> 使用 setup()
beforeMount -> onBeforeMount
mounted -> onMounted
beforeUpdate -> onBeforeUpdate
updated -> onUpdated
beforeUnmount -> onBeforeUnmount
unmounted -> onUnmounted
errorCaptured -> onErrorCaptured
renderTracked -> onRenderTracked
renderTriggered -> onRenderTriggered
activated -> onActivated
deactivated -> onDeactivated
setup
1. 一个组件选项,在组件被创建之前,props 被解析之后执行。它是组合式 API 的入口。
2. 在setup函数中 this 还不是组件实例,this 此时是 undefined
3. 在模版中需要使用的数据和函数,需要在 setup 返回。
ref
1. ref函数,常用于简单数据类型定义为响应式数据
2. 再修改值,获取值的时候,需要`.value`
3. 在模板中使用ref申明的响应式数据,可以省略`.value`
reactive
reactive是一个函数,它可以定义一个复杂数据类型,成为响应式数据。
toRef
toRef是函数,转换响应式对象中某个属性为单独响应式数据,并且值是关联的。
<template>
<div>
<h1>{{ msg }}</h1>
<button @click="count++">count is: {{ count }}</button>
<p>num--{{ num }} <span @click="num++">++++</span></p>
<p>x: {{ page.x }} * 100 = {{ flag }}</p>
<p>y: {{ page.y }}</p>
</div>
</template>
<script>
import {
ref,
reactive,
onMounted,
onUnmounted,
onUpdated,
computed,
} from "vue";
export default {
name: "HelloWorld",
props: {
msg: String,
},
data() {
return {
count: 0,
};
},
setup() {
const num = ref(123);
const page = reactive({
x: 0,
y: 0,
});
const move = (e) => {
page.x = e.pageX;
page.y = e.pageY;
};
// 生命周期:挂载dom后
onMounted(() => {
// console.log(num);
console.log("挂载dom后");
document.addEventListener("mousemove", move);
});
onUpdated(() => {
console.log("更新组件后");
});
const flag = computed(() => {
return page.x * 100;
});
// 生命周期:挂载销毁后
onUnmounted(() => {
console.log("卸载销毁后");
document.removeEventListener("mousemove", move);
});
return {
num,
page,
flag,
};
},
};
</script>