'How to interpolate prop into the <router-link>?
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)
Solution 1:[1]
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).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
