Reputation: 245
I' m trying to achieve dynamic Uri templating in vue
Data :
new Vue({
el: '#app',
data: {
"navigation": [
{
"url": "https://domainxxx.org/{param1}",
"param1": "John",
"param2": "123"
},
{
"url": "https://otherdomain.org/{param2}",
"param1": "Other",
"param2": "43213432143214"
}
]
}})
Code:
<div id="app">
<template v-for="row in navigation">
<br/>
<a :href="row.url"> Hello </a> <<<<<<<<<<<<<<<
</template>
</div>
For this example expected link (href)
Is there any option to do templating during binding property ?
Upvotes: 1
Views: 244
Reputation: 245
Jst to have complete answear Thank you @donMateo I will accept your answear because it lead me to solve this. Im not sure at the moment what is best method use computed poperty or function, function was easier so posting solution.
So answear is to use function
<a :href="getUrl(url,data)"> Hello </a>
This is a case when we have dynamic url tempalte for each object
Ive found two ways for doing templating - https://medialize.github.io/URI.js/uri-template.html and some custom code that solve my case
getUrl: function (url,data)
{
var keys = Object.keys(data);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
url = url.replace(/{[^{}]+}/g, data[key]);
}
return url;
}
Upvotes: 0
Reputation: 3022
DonMateo's answer is correct: you need to use a custom method that renders the url for each row. Here I use Mustache, but you can use a template language of your choice:
Mustache.tags = ['{', '}'] // Using custom delimiters, since the default is {{ }}
new Vue({
el: '#app',
data: {
"navigation": [
{
"url": "https://domainxxx.org/{param1}",
"param1": "John",
"param2": "123"
},
{
"url": "https://otherdomain.org/{param2}",
"param1": "Other",
"param2": "43213432143214"
}
]
},
methods: {
getURL: function(row) {
return Mustache.render(row.url, row)
}
}
})
And the template:
<a :href="getURL(row)"> Hello </a>
Upvotes: 1
Reputation: 2394
You can achieve this using computed properties + any templating engine or simple string concatenation.
BUT, in your example I don't se any pattern between two urls, can you tell me why you want to parametrize these?
EDIT: Ok, got this ;) You need to store unique url templates. So in this case I would add url extraction method:
methods: {
getUrl: function(navigation) {
return TemplateEngineOfYourChoice.Template(navigation.url, navigation);
}
}
<a :href="getUrl(row)"> Hello </a>
Upvotes: 2