问题
I have a SPA made in VUE and Laravel.
Laravel returns API request and VUE create the frontend using the received data.
In a few cases, I have some HTML code returned as compiled data by API engine having links inside.
I would like to use these links in vue router but if I return the API having code like this:
JSON code
{
comment: {
'bla <strong>bla</strong> bla <router-link :to="name:\'page\'">text</router-link>'
}
}
Then I use the JSON code in my component template like:
<div v-html={comment}></div>
But this is not rendered and returned as plain HTML: I see the bold but not the <a href='page'>text...
as I need but I got <router-link...
as plain text.
Simple JSFiddle test
Here a demo test where I try to replicate the issue. If you click on Foo Link (Top menu) it open a component having props data with HTML code inside. The bold is shown properly but the router link is not rendered
data: {
msg: 'Hello World',
comment : '<div class="comment">This is a <strong>bold</strong> <br>
this should be a <router-link :to="{\'name\':\'home\'}">
router link</router-link></div>'
}
How can I force the vue-router render in this case?
回答1:
Fixed by my own: https://jsfiddle.net/uncoke/92x0jhr1/
Here my own fix:
The custom data with link:
{ team: "<a href=\"/club/"+team.id+"\" data-to='{\"name\": \"team\",\"params\":{\"teamId\":"+ team.id+"}}'>"+ team.team+"</a> "+userCode,
....}
The click Listener
mounted() {
window.addEventListener('click', event => {
let target = event.target;
if (target && target.href && target.dataset.to) {
event.preventDefault();
const url = JSON.parse(target.dataset.to);
//router.push({ name: 'user', params: { userId: '123' } })
this.$router.push(url);
}
});
}
来源:https://stackoverflow.com/questions/56802857/laravel-eloquent-data-or-simple-props-to-create-a-custom-vue-router-link-in-vue