Search code examples
vue.jsvuejs3v-forvue-composition-api

Vue - v-for with modifying values


Template:

<template>
  <nav>
    <router-link :to="key" v-for="(value, key) in state.menu" :key="key">{{value}} | </router-link>
  </nav>
</template>

Code:

export default {
  setup() {

    const menu = ['home', 'news', 'about'];

    const state = reactive({
      menu: {}
    }); 

    menu.map(item => {
      state.menu[item] = Common.locs[item];
    });

    return {
      Common,
      state,        
    }

  }
}

I want to update

:to="key" 

to run it through some filter or function to modify it to add the prefix something like "/other/", so instead of rendered

<a href="/home" ...>

I would have

<a href="/other/home" ... >

(Of course, const menu values are mocked for the sake of example; those are fetched from the service so I have no saying in that, and I don't want to modify them after fetching for other reasons)

So in general, my question is not regarding proper routing, but how do you modify v-for data (in my case: key) in the runtime if you need to?

(I guess I could modify mapping line into

state.menu["/other/" + item] = Common.locs[item];

but I want to preserve state.menu as I wrote. I want change to happen during the v-for rendering.)


Solution

  • Have you tried the template literal:

    <template>
      <nav>
        <router-link :to="`/other/${key}`" v-for="(value, key) in state.menu" :key="key">{{value}} | </router-link>
      </nav>
    </template>