gpt4 book ai didi

vuejs3 - Vue3 Composition Api 检查空槽

转载 作者:行者123 更新时间:2023-12-05 04:44:42 25 4
gpt4 key购买 nike

第一个使用 Vue3 的项目,试图确定命名插槽是否在给定页面上提供了内容。

在我的模板中我有这个:

<div
:class="{ 'py-20': hasTopContent }"
>
<slot name="top-content" />
</div>

在我的代码中有以下内容:

setup (_, { slots }) {

const hasTopContent = computed((slots) => {

console.log(slots.topContent);

return slots.topContent && slots.topContent().length;
});

return {
hasTopContent
}
}

上面的 console.log 正在返回 TypeError: Cannot read properties of undefined (reading 'topContent')。我错过了什么?谢谢!

最佳答案

Michal Levý是对的

var Main = {
components: {
'my-component': MyComponent,
},
data() {
return {
}
},
methods: {
}
};
const app = Vue.createApp(Main);
app.mount("#app")
<html>
<head>
<style>
.my-component {
background-color: #fafafa;
padding: 5px 20px 20px 20px;
}
</style>
</head>
<body>
<div id="app">
<h3>With top slot</h3>
<my-component class='my-component'>
<template v-slot:top>
<h4>Top Slot</h4>
</template>
</my-component>
<h3>Without top slot</h3>
<my-component class='my-component'>
</my-component>
<hr style='padding: 20px 20px 20px 20px;' />
</div>
<script src="//unpkg.com/vue@next"></script>
<script type="text/x-template" id="my-component">
<div
:class="{ 'py-20': hasTopContent }">
<slot name="top" />
hasTopContent: {{hasTopContent}}
</div>
</script>
<script type="text/javascript">
var MyComponent = {
template: '#my-component',
setup(_, { slots }) {
const hasTopContent = Vue.computed(() => {
return slots.top && slots.top().length > 0;
});
return { hasTopContent }
}
}
</script>
</body>
</html>

关于vuejs3 - Vue3 Composition Api 检查空槽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69282145/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com