我想重构this教程中关于渲染函数的代码,以使用组合API。除了onClick函数中的context.emit("update:activeTabId", tab.props.tabId);
行之外,其他一切都运行正常。控制台记录tab.props.tabId
显示onClick函数可以正常工作并正确读取tabId,但update:activeTabId
不更新activeTabId
值。有没有其他方法可以在组合API中使用sync修饰符来发出事件,或者我做错了什么?
下面是我的代码:
- App.vue
<template>
<!-- eslint-disable-next-line -->
<tab-container v-model:activeTabId="activeTabId">
<tab tabId="1">Tab #1</tab>
<tab tabId="2">Tab #2</tab>
<tab tabId="3">Tab #3</tab>
<tab-content tabId="1">Content #1</tab-content>
<tab-content tabId="2">Content #2</tab-content>
<tab-content tabId="3">Content #3</tab-content>
</tab-container>
</template>
<script>
import {ref} from 'vue'
import {Tab, TabContent, TabContainer} from './components/tabs.js';
export default {
components: {
Tab,
TabContent,
TabContainer
},
setup() {
const activeTabId = ref('1');
return {
activeTabId,
};
},
};
</script>
- tabs.js
import { h } from "vue";
export const TabContainer = {
props: {
activeTabId: {
type: String,
required: true,
},
},
emits: ['update:activeTabId'],
setup(props, context) {
const $slots = context.slots.default();
const tabs = $slots
.filter((x) => x.type === Tab)
.map((tab) =>
h(tab, {
class: {
tab: true,
active: props.activeTabId === tab.props.tabId,
},
onClick: () => {
console.log(tab.props.tabId)
context.emit("update:activeTabId", tab.props.tabId);
},
})
);
const content = $slots.find(
(slot) =>
slot.props.tabId === props.activeTabId && slot.type === TabContent
);
return () => [
h(() => h("div", { class: "tabs" }, tabs)),
h(() => h("div", content))
];
},
};
const tabItem = (content) => ({
...content,
props: {
tabId: {
type: String,
required: true,
},
},
setup(_, context) {
return () => h("div", context.slots.default())
}
});
export const Tab = tabItem({ name: "Tab" });
export const TabContent = tabItem({ name: "TabContent" });
发布于 2020-12-29 16:32:31
经过一些研究后,我发现activeTabId
正在更新,但TabContainer不知何故没有考虑它的反应性价值,所以它没有变化。我已经用watchEffect
封装了所有的TabContainer逻辑,监视activeTabid
的变化,现在它可以正常工作了!
https://codesandbox.io/s/solitary-currying-50ick?file=/src/App.vue
https://stackoverflow.com/questions/65491163
复制相似问题