Reputation: 4255
I have a use case inside a component where within a description string (contained as text within a b-card-text Bootstrap Vue element), I want one particular word to be replaced by an internal link using '` if the user is logged in (as determined by the value of another variable), but if not, then just use the default text. Normally I would use a computed value for something like this, but I can't get it to return just the router link. The text is fairly long, so I don't want to include all of it in the computed value.
Here's what I tried:
computed: {
accountPageLink() {
return this.authUserIsAccountOwner ?
'<router-link :to="/account"></router-link>' :
'Account';
}
}
But that just returns a string, and if I remove the quotes from the link, I get an error saying Support for the experimental syntax 'jsx' isn't currently enabled
.
Is there a way to do what I want to do with just replacing the one word dynamically in the string?
Upvotes: 0
Views: 1154
Reputation: 2616
I normally do this logic in the template.
<router-link v-if="authUserIsAccountOwner" to="/account">Edit Account</router-link>
<template v-else>Account</template>
Alternatively, you can pass in this computed HTML into the v-html
binding of the element:
<div v-html="accountPageLink"></div>
If you're pattern matching to find the word(s) you want to replace, you can do that in the computed property and use the v-html
binding to insert it into your template element. For example:
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-html="linkifiedText"></div>
</div>
<script>
var app = new Vue({
el: '#app',
data() {
return {
someText: 'Lorem ipsum dolor account sit amet',
authUserIsAccountOwner: true,
};
},
computed: {
linkifiedText() {
return this.authUserIsAccountOwner
? this.someText.replace('account', '<a href="/account">linkifiedAccount</a>')
: this.someText;
},
}
});
</script>
Upvotes: 2