.sync修饰符
比如之前一直这样写:(update事件正常写)
current-page.sync="currentPage"
但是vue3就不行了,改成
v-model:current-page="currentPage" 就可以了
vue3中组件跳转之后页面不显示
可能的原因有很多,大部分是路由和组件引入的问题,除此之外还要注意内置组件transition
的使用带来的问题。仅支持单个元素或组件作为其插槽内容。如果内容是一个组件,这个组件必须仅有一个根元素。
这一点在官方文档可以看到。
Image.png
Vue3中使用component :is 加载组件
1.不使用setup语法糖,这种方式和vue2差不多,is可以是个字符串
- 使用setup语法糖,这时候的is如果使用字符串会加载不出来,得使用组件实例
<template>
<Child1 />
<Child2 />
<component :is="currentComp"></component>
<el-button @click="compChange">切换组件</el-button>
</template>
<script setup>
import { shallowRef, ref } from 'vue'
import Child1 from './Child1.vue'
import Child2 from './Child2.vue'
//这里用ref的话,vue给出警告Vue接收到一个组件,该组件被制成反应对象。这可能会导致不必要的性能开销,应该通过将组件标记为“markRaw”或使用“shallowRef”而不是“ref”来避免。
// 如果使用 markRaw 那么currentComp将不永远不会再成为响应式对象。 所以得使用 shallowRef
const currentComp = shallowRef(Child1)
// 1)切换组件
// const compChange = () => {
// if(currentComp.value == Child1) {
// currentComp.value = Child2
// }else {
// currentComp.value = Child1
// }
// 2)也可以动态切换组件,这样就不用在上面引入了
currentComp.value = defineAsyncComponent(() => import('./Child2.vue'))
}
</script>
-
如果 import 里面有变量
如果 import 里面有变量,上面的方法2 本地开发没问题,但打包部署后引入多级目录下会报错
image.png
vite2中的解决方案:import.meta.glob
import.meta.glob 获取到的文件就是懒加载的,避免了使用 import 语句, 所以打包后不会报错不存在动态引入了
const compChange = path => {
// 首先把需要动态路由的组件地址全部获取
const modules = import.meta.glob('../views/**/*.vue')
// 然后动态路由的时候这样来取
currentComp.component = defineAsyncComponent(modules[`../views/${path}.vue`])
}