Home > Blockchain >  How to interpolate prop into the <router-link>?
How to interpolate prop into the <router-link>?

Time:01-26

If I did this {{ name }}, I got "campaigns"

I want to render that into my link

<router-link :to="'/'   '123'   '/'   item.id"> {{ item.name }}</router-link>

I've tried replace '123' with {{ name }}

<router-link :to="'/'   {{ name }}   '/'   item.id"> {{ item.name }}</router-link>

I kept getting

Failed to compile. ./src/components/Table.vue?vue&type=template&id=783f90ce& (./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"5c3eaf11-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--1-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Table.vue?vue&type=template&id=783f90ce&) Module build failed (from ./node_modules/vue-loader/lib/loaders/templateLoader.js): SyntaxError: Unexpected token (1:1767)

./src/components/Table.vue?vue&type=template&id=783f90ce& (./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"5c3eaf11-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--1-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Table.vue?vue&type=template&id=783f90ce&) Module build failed (from ./node_modules/vue-loader/lib/loaders/templateLoader.js): SyntaxError: Unexpected token (1:1767)

CodePudding user response:

Just use it without {{}} :

<router-link :to="'/'   item.name   '/'   item.id"> {{ item.name }}</router-link>

or with string template :

<router-link :to="`/${item.name}/${item.id}`"> {{ item.name }}</router-link>

CodePudding user response:

Mustache syntax is invalid within html attributes. That is, this is invalid:

<router-link
  :to="'/'   '123'   '/'   item.id"
>
  {{ item.name }}
</router-link>

What is correct syntax is:

<router-link
  :to="`/${item.name}/${item.id}`"
>
  {{ item.name }}
</router-link>

Moreover, I would recommend checking out passing properties to the route object within the documentation. This will show you that you can declare variables within the router such as :id.

I would make another recommendation aside from the above to point out that if this was defined as a computed property of the component, it is easily both viewable in devtools and future debugging (e.g. you probably want to return empty string if the object props are undefined).

  •  Tags:  
  • Related