简体   繁体   中英

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)

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>

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 (eg you probably want to return empty string if the object props are undefined).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM