0

我想重构教程中关于渲染函数的代码以使用合成 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" });
4

1 回答 1

0

经过一些研究,我发现它activeTabId正在更新,但 TabContainer 不知何故不认为它是反应值,所以它没有改变。我已经将所有 TabContainer 逻辑都包含watchEffect在监视activeTabid更改中,现在它可以正常工作了!

https://codesandbox.io/s/solitary-currying-50ick?file=/src/App.vue

于 2020-12-29T16:32:30.550 回答