Search code examples
javascriptvue.jsvuejs3watchvue-composition-api

Mutating ref value from watcher in Vue 3 with Composition API


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.


Solution

  • Since selectedTitle is ref try with

    selectedTitle.value = tabTitles.value[0];