vue3.0特性全面刨析
新特性:
Performance:
- 重写了虚拟Dom的实现(跳过静态节点,只渲染动态节点)
- updata性能提高了1.3-2.0倍
- SSR性能提高了2-3倍
Tree shaking:
- 可以将无用模块“编辑”,仅打包需要的
Fragment
- 不再限于模板的单个根节点
< Teleport >
- 以前称为port,译作传送门
< Suspense >
- 可以在嵌套层级中等待嵌套的异步依赖项
Typescript
- 更好的Typescript支持
- custom Render API
自定义渲染API
- 用户可以尝试WebGL自定义渲染器
Composition API
- 组合式API,替换原有的options API
- 根据逻辑相关性,组织代码,提高可读性、可维护性
- 更好的重用逻辑代码(避免mixin 混入时命名冲突的问题)
- 依然可以沿用options API
Proxy
- 响应式不再基于Object.defineProperty
基于vue/cli配置vue3.0
-
vue-cli-plugin-vue-next
基于vite实现vue3.0共工程化部署
由vue作者由雨溪开发的web工具
npm init vite-app xxx
cd xxx
npm install
npm run dev
setup等10种响应式API
setup
setup是一个新的组件选项,作为在组件内Composition Api的入口点
- 初始化props和beforecreate之间被调用
- 可以接受props和context
- this在props不可用
props是响应式的,可以基于watchEffect/watch监听,结构赋值则无效
返回的值可以直接在模版中渲染
模板ref的使用
ref
可以接受一个参数值并返回一个可响应式且改变的ref对象
- ref对象拥有一个指向内部值的单一属性.value
- 当ref在模版中使用的时候,它会自动结构,无需在模版中额外写.value
reactive
接受一个普通对象然后返回该普通对象的响应式代理,等同于2.x的vue.obserable()
- 响应式转换是”底层的“会影响对象内部所有嵌套的属性
unref/toRef/toRefs/isRef/isProxy/isReative/isReadonly
readonly
传入一个对象(响应式或普通对象或者ref,返回一个原始对象的只读代理),对象内部嵌套的属性也是底层的
computed
传入一个getter函数,返回一个默认不可修改的ref对象
或者传入一个拥有set和get函数的对象,创建一个可修改的计算状态
生命周期函数
在vue3.0中对生命周期做了以下改动:
- beforeCreate -> 请使用 setup()
- created -> 请使用 setup()
- beforeMount -> onBeforeMount
- mounted -> onMounted
- beforeUpdate -> onBeforeUpdate
- updated -> onUpdated
- beforeDestroy -> onBeforeUnmount
- destroyed -> onUnmounted
而在Vue3.0中,Vue2.x Options API形式的生命周期钩子函数和新的Composition API都可以使用:
import { onMounted } from 'vue'
export default {
mounted() {
console.log('>>>>>> mounted 1')
},
setup() {
onMounted(()=>{
console.log('>>>>> mounted 2')
})
}
}
整体代码如下:
import { computed, onBeforeUnmount, reactive, readonly,onMounted,ref,onBeforeUpdate,onUpdated,onUnmounted,onBeforeMount} from 'vue'
export default {
props: {
initCount:String
},
setup(props) {
const countOps = useCount(props.initCount)
console.log("相当于 vue2.x 中 beforeCreated, created")
function useCount(prop:String|undefined) {
const state = reactive({ count: prop })
const increase = () => { state.count}
const reset = () => { state.count = '0' }
return { state, increase, reset }
}
onBeforeMount(()=>{
console.log("App ===> 相当于 vue2.x 中 beforeMount")
}),
onMounted(()=>{
console.log("App ===> 相当于 vue2.x 中 mounted")
}),
onBeforeUpdate(()=>{
console.log("App ===> 相当于 vue2.x 中 beforeUpdate")
}),
onUpdated(()=>{
console.log("App ===> 相当于 vue2.x 中 updated")
}),
onBeforeUnmount(()=>{
console.log("App ===> 相当于 vue2.x 中 beforeDestroy")
}),
onUnmounted(()=>{
})
return { countOps }
},
}