1.查看vue cli的版本
vue --version // 我的版本 @vue/cli 4.5.13
2.安装vue cli
npm install -g @vue/cli
#OR
yarn global add @vue/cli
3.将vue cli升级到最高版本 只有最高版本才支持创建项目的时候才有vue3的使用选项
npm update -g @vue/cli
#或者
yarn global upgrade --latest @vue/cli
4.创建vue3项目步骤
选择以下几项
=> 选择3.x
Vue2与Vue3的对比
- 对TypeScript支持不友好(所有属性都放在了this对象上,难以推倒组件的数据类型)
- 大量的API挂载在Vue对象的原型上,难以实现TreeShaking。
- 架构层面对跨平台dom渲染开发支持不友好
- CompositionAPI。受ReactHook启发
- 更方便的支持了 jsx
- Vue 3 的 Template 支持多个根标签,Vue 2 不支持
- 对虚拟DOM进行了重写、对模板的编译进行了优化操作...
生命周期对应表
vue3的新生命周期选项 API 生命周期选项和组合式 API 之间的映射
beforeCreate -> use setup()
created -> use setup()
beforeMount -> onBeforeMount
mounted -> onMounted
beforeUpdate -> onBeforeUpdate
updated -> onUpdated
beforeUnmount -> onBeforeUnmount
unmounted -> onUnmounted
errorCaptured -> onErrorCaptured
renderTracked -> onRenderTracked
renderTriggered -> onRenderTriggered
setup
setup() 函数是 vue3 中,专门为组件提供的新属性。它为我们使用 vue3 的 Composition API 新特性提供了统一的入口, setup 函数会在 beforeCreate 、created 之前执行, vue3也是取消了这两个钩子,统一用setup代替, 该函数相当于一个生命周期函数,vue中过去的data,methods,watch等全部都用对应的新增api写在setup()函数中
setup(props, context) {
context.attrs
context.slots
context.emit
return {
}
}
-
props: 用来接收 props 数据
-
context 用来定义上下文, 上下文对象中包含了一些有用的属性,这些属性在 vue 2.x 中需要通过 this 才能访问到, 在 setup() 函数中无法访问到 this,是个 undefined
-
返回值: return {}, 返回响应式数据, 模版中需要使用的函数
reactive
reactive() 函数接收一个普通对象,返回一个响应式的数据对象, 想要使用创建的响应式数据也很简单,创建出来之后,在setup中return出去,直接在template中调用即可
<template>
{{name}} // test
<template>
<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from 'vue';
export default defineComponent({
setup(props, context) {
let state = reactive({
name: 'test'
});
return state
}
});
</script>
ref()
ref() 函数用来根据给定的值创建一个响应式的数据对象,ref() 函数调用的返回值是一个对象,这个对象上只包含一个 value 属性, 只在setup函数内部访问ref函数需要加.value
<template>
<div class="mine">
{{count}} // 10
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
export default defineComponent({
setup() {
const count = ref<number>(10)
// 在js 中获取ref 中定义的值, 需要通过value属性
console.log(count.value);
return {
count
}
}
});
</script>
computed()
该函数用来创造计算属性,和过去一样,它返回的值是一个ref对象。 里面可以传方法,或者一个对象,对象中包含set()、get()方法
import { computed, defineComponent, ref } from 'vue';
export default defineComponent({
setup(props, context) {
const age = ref(18)
// 根据 age 的值,创建一个响应式的计算属性 readOnlyAge,它会根据依赖的 ref 自动计算并返回一个新的 ref
const readOnlyAge = computed(() => age.value++) // 19
return {
age,
readOnlyAge
}
}
});
</script>
watch()
watch 函数用来侦听特定的数据源,并在回调函数中执行副作用。默认情况是懒执行的,也就是说仅在侦听的源数据变更时才执行回调。