用组成API在VUE 3中突变参考值

发布于 2025-02-11 21:50:34 字数 890 浏览 1 评论 0原文

我试图在手表功能中突变ref,但似乎不起作用。我正在使用手表注意如果我的数组长度更改,则需要将旧长度与新长度进行比较,然后将ref(selectionTitle)变为newValue,如果NewValue小于OldValue。

 setup() {
    const slots = useSlots();
    const tabTitles = computed(() =>
      slots.default()[0].children.map((tab) => tab.props.title)
    );
    const tabTitlesLength = computed(() => tabTitles.value.length);
    let selectedTitle = ref(tabTitles.value[0]);
    provide("selectedTitle", selectedTitle);
    provide("tabTitles", tabTitles);
    watch(tabTitlesLength, (currentValue, oldValue) => {
      if (currentValue < oldValue) {
        selectedTitle = tabTitles.value[0];
      } else {
        console.log("fuera del if");
      }
    });
    return {
      tabTitles,
      selectedTitle,
      tabTitlesLength,
    };
  },

使用该代码,SelectedTitle Ref永远不会更改它总是具有每当计算属性更改(TabTitles)时收到的最后一个值。我只是不明白为什么其他一切似乎都很好。

I'm trying to mutate a ref within a watch function but it doesn't seem to work. I'm using watch to pay attention if my array length changes, whenever that changes I need to compare the old length with the new one and then mutate a ref (selectedTitle) if the newValue is less than the oldValue.

 setup() {
    const slots = useSlots();
    const tabTitles = computed(() =>
      slots.default()[0].children.map((tab) => tab.props.title)
    );
    const tabTitlesLength = computed(() => tabTitles.value.length);
    let selectedTitle = ref(tabTitles.value[0]);
    provide("selectedTitle", selectedTitle);
    provide("tabTitles", tabTitles);
    watch(tabTitlesLength, (currentValue, oldValue) => {
      if (currentValue < oldValue) {
        selectedTitle = tabTitles.value[0];
      } else {
        console.log("fuera del if");
      }
    });
    return {
      tabTitles,
      selectedTitle,
      tabTitlesLength,
    };
  },

With that code the selectedTitle ref never change it always has the last value that received whenever the computed property changes (tabTitles). I just don't understand why since everything else seems to work just fine.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

猫性小仙女 2025-02-18 21:50:34

由于selectedtitle是ref尝试

selectedTitle.value = tabTitles.value[0];

Since selectedTitle is ref try with

selectedTitle.value = tabTitles.value[0];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文