0

The following code works fine. When we change the language the text gets updated correctly thanks to the ref:

const mainNavigationLinks = computed(() => [
  { label: context.root.$t('navigationMenu.home') },
  { label: context.root.$t('navigationMenu.tickets') },
])

return {
  mainNavigationLinks,
}

But what we would really like is to have the mainNavigationLinks as a reactive object, so we can add and remove items from the array and have Vue update the components accordingly with the correct translations by using the ref within the array. According to the Vue docs this should be possible

However, when we try the code below we see that the label is no longer reactive:

const mainNavigation = reactive([
  { label: context.root.$t('navigationMenu.home') },
  { label: context.root.$t('navigationMenu.tickets') },
])

const mainNavigationLinks = computed(() => mainNavigation)

What are we missing here to be able to add items to the array and still have it reactive? Thank you for your help.

0

1 Answer 1

1

It seems like what you want is to have the array be reactive, but the items within the array be computed properties.

const mainNavigation = reactive([
  { label: computed(() => context.root.$t('navigationMenu.home')) },
  { label: computed(() => context.root.$t('navigationMenu.tickets')) },
])

Alternatively, you might be able to get away with not using computed at all here, as long as each label property refers to a function that you have to call:

const mainNavigation = reactive([
  { label: () => context.root.$t('navigationMenu.home') },
  { label: () => context.root.$t('navigationMenu.tickets') },
])

That's the main idea: each label needs to be evaluated at the time it is used, which is why it must be either a computed property (you benefit from caching) or a function. Your code doesn't work because you are getting the label translations immediately when you constructed the array.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the help. What you say seems logical but when I try the computed version it complains with type check failed for prop "label". Expected Number, String, got Object . With the anonymous functions used as an IIFE it displays the text but it loses reactivity again.
For point #1 you might need to manually unwrap it :label="mainNavigation[0].label.value"; for #2 it shouldn't be invoked immediately in the array, it has to be kept in the array as a function that you call like :label="mainNavigation[0].label()", if that is what you did but it still doesn't work then that's odd and I have no explanation.
Weird that we need to manually unwrap it. Made an issue on GitHub for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.