【发布时间】:2021-11-13 04:36:02
【问题描述】:
下面的Options API代码好像不能转换成<script setup>:
<template>
<div>
<component :is="layout">
<router-view/>
</component>
</div>
</template>
<script>
const defaultLayout = 'default'
import Dark from './layouts/dark.vue'
import Light from './layouts/light.vue'
import Default from './layouts/default.vue'
export default {
name: 'App',
components: {
Dark,
Light,
Default
},
computed: {
layout () {
return (this.$route.meta.layout || defaultLayout)
}
}
}
</script>
我的尝试:
<script setup>
import { computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import Dark from './layouts/dark.vue'
import Light from './layouts/light.vue'
import Default from './layouts/default.vue'
const router = useRouter()
const route = useRoute()
const defaultLayout = 'default'
const layout = computed(() => route.meta.layout || defaultLayout )
</script>
结果:
<script setup> 选项不加载任何布局,而仅加载 <default>、<dark> 或 <light> 块,例如:
<div id="app">
<default>
...
...
</default>
</div>
根据文档here,我们可以使用三元:
<component :is="someCondition ? Foo : Bar" />
但这并不理想。因为您可能有超过 2 个动态组件需要解决。我们不能让三元组太长。我们可以吗?
有什么想法吗?
【问题讨论】:
-
:is="route.meta.layout || 'defaultLayout'"或:is="route.meta.layout ? route.meta.layout : 'defaultLayout'"怎么样 -
我有一个类似的问题,关于使用
component :is=""和script setup。 Hope it will help you -
@BoussadjraBrahim 做到了。没有运气
标签: vue.js vue-component vuejs3