我想重构本教程中关于渲染函数的代码以使用合成 API。一切正常,除了context.emit("update:activeTabId", tab.props.tabId);
onClick 函数中的行。控制台记录tab.props.tabId
显示 onClick 函数可以正常工作并正确读取 tabId,但update:activeTabId
不会更新activeTabId
值。是否有另一种方法可以在 Composition API 中使用同步修饰符发出事件,或者我做错了什么?
这是我的代码:
---- 应用程序.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" });