[Vuejs]-The lifecycle of functions in Vue3 templates

0👍

The reason why the rendering is called twice is related to the lifecycle of vue components. Vue will always render the component, when a reactive value changes. As you use a function inside a template, this will be called on each render cycle of the component.
In your example the info.value update will trigger a rerender. Also if using a function, vue needs to allways trigger a rerender if you change any reactive value.

That is also why you should not use functions inside the template. Whenever possible you should use computed properties and apply it inside the template. The advantage is, that vue will internally cache the value of the computed property and only update the component, if some of the values you use inside is updated.

You should make sure, you understand how the vue lifecycle works.

A better approach would be to use a computed property that is rendered inside your template. The following shows an example that might work for you.

const direction = ref('');

const pageParam = computed(() => {
  try {
    let url_string = null;
    switch (direction.value) {
      case 'next':
        url_string = info.value.next;
        break;
      case 'previous':
        url_string = info.value.previous;
        break;
      default:
        return route.query.page;
    }

    const url = new URL(url_string);
    return url.searchParams.get('page');
  } catch (err) {
    console.log(err);
    return '1'; // you need to return the fallback page
  }
});

Inside the template you use

<template>
  <span class='current-page'>
    {{ pageParam }}
  </span>
</template>

Leave a comment