Home > Back-end >  Update array properties dynamically in Vue 3 composition API when route param changes
Update array properties dynamically in Vue 3 composition API when route param changes

Time:08-24

My component (Vue 3 with composition API script setup) has a property linkList. This shall be updated whenever the route param id changes.

Example

When calling this component on /user/1, then linkList shall look like this:

{id: 1, name: 'foo'},
{id: 1, name: 'bar'}

This is my current code:

<script setup>

const route = useRoute();
const idRouteParam = computed(() => route.params.id);

const linkList = [
{
  id: idRouteParam,
  name: 'foo',
},
{
  id: idRouteParam,
  name: 'bar',
}
];

watch(
  idRouteParam,
  () => {
    console.log(idRouteParam);
  },
  { immediate: true },
);

</script>

The problem is: linkList is only updated after the page is refreshed, i.e. the component is re-created. When idRouteParam changes (example: /user/2), then linkList has the original values from user 1. I thought that I could update it in the watcher but I guess I'm missing some piece of the puzzle.

CodePudding user response:

The linkList should be also defined as a computed property :

const linkList = computed(()=>[
{
  id: idRouteParam,
  name: 'foo',
},
{
  id: idRouteParam,
  name: 'bar',
}
]);

  • Related