vue3快速上手(二)
teleport
Teleport,vue2中书写的组件结构和实际生成的dom结构成映射关系,vue3中可以使用Teleport改变这种映射关系,指定Teleport中的组件插入到指定的dom中
例子
在public/index.html中为#app添加一个兄弟节点#app2
//APP.vue
<h1>这是App中的内容</h1>
<Teleport to="app2">
<div style="color:red">这是app2中的内容</div>
</Teleport>
v-model
v-model的改变,vue2中双向数据绑定可以使用v-model和.sync,所以在v-model中去掉了.sync,只是用v-model
- v-model绑定的属性名由原来的value变成了modelValue,事件名变成了update:modelValue
<ChildComponent
:modelValue="pageTitle"
@update:modelValue="pageTitle = $event"
/>
相当于
<ChildComponent v-model="pageTitle" />
- v-model可以使用参数,用来替换掉.sync的功能
举个例子
//ChildComponent组件
<template>
<input type="text" :value="inpText" @input="handleInput">
</template>
<script>
export default {
props:['inpText'],
methods:{
handleInput(e){
console.log(this.$emit)
this.$emit('update:inpText',e.target.value);
}
}
}
</script>
在childComponent中传入inpText的属性。输入时触发update:inpText事件
<child-component v-model:inpText="inpText"></child-component>
使用v-model:inpText来进行双向数据绑定
异步组件
异步组件
在项目中,我们可能需要将代码拆分成很多快,在需要的时候才异步加载相应的模块,来达到提高首屏加载速度的需要,在vue3中提供了defineAsyncComponent来定义异步组件,要求返回一个Promise。
util.js
//得到一个异步组件
export function getAsyncComponent(path){
return defineAsyncComponent({
loader:async ()=>{
await delay();
if(Math.random()<0.5){
throw new TypeError()
}
return import(`../components/${path}.vue`);
},
loadingComponent:Loading,
errorComponent:{
render(){
return h(Error,"出错")
}
}
})
}
Home.vue
const Block1 = getAsyncComponent('Block1')
const Block2 = getAsyncComponent('Block2')
export default {
name: "App",
components: {
Block1,
Block2
},
};
其中右边两个都是异步组件,在进入home页面才会异步加载
踩坑
这里踩了个import的坑,动态import的时候不能够直接传入一个变量进去,必须要给出一些信息,比如上面的代码中使用的是…components${path}.vue,这样才能够推断出来,坑了我差不多一个小时…