1

I have a js file containing array and objects. I need to style some properties from these arrays. For example

myArray= [
  {
    id: 1,
    name: 'honda',
    description: 'to buy the latest car, click here'
  },
  {
    id: 2,
    name: 'tesla',
    description: 'to buy the latest car, click here'
  }
]

Let's say I want to style the description property so that I can bind a link there. I figure that the way to do it is to use raw html. But in my case, I'm going to include it to my array. Is this possible? I have tried to search this question everywhere but there's no explanation for this case. Thank you so much.

6
  • 1
    sure, description: '... <a href="#">...</a>...', then use <span v-html="item.description"></span>, make sure its not user supplied though, else XSS is possible. The only issue comes if you want to do vue in the string, ie a @click="$router.push('/')" etc, then your want to use the runtime complier Commented Feb 23, 2021 at 2:39
  • 2
    Your array values can contain HTML. In order to display it, you would need to use v-html as you already indicated, eg <p v-for="obj in myArray" :key="obj.id" v-html="obj.description"></p> Commented Feb 23, 2021 at 2:40
  • @LawrenceCherone ahh, I see! thank you so much for you answer! Commented Feb 23, 2021 at 2:53
  • @Phil thank you for your explanation! does this also work if not all description property are styled? I mean, for example, in another new object (another car), I don't want to add any v-html in the description property. Commented Feb 23, 2021 at 2:55
  • 1
    v-html doesn't require there to be HTML tags present. It will just output your description value as-is Commented Feb 23, 2021 at 2:58

1 Answer 1

2

You can use any html styled code in your Array such as below.

myArray= [
  {
    id: 1,
    name: 'honda',
    description: '<a href="https://www.honda.com">to buy the latest car, click here</a>'
  },
  {
    id: 2,
    name: 'tesla',
    description: '<a href="https://www.tesla.com" style="font-size:50px">to buy the latest car, click here</a>'
  }
]

And in your templete you would use: like

...
<div v-for="car in myArray" :key="car.id">
    <p v-html="car.description"></p>
</div>

Check out this code.

Check out this codepen.

You can check out the vuejs documentation for more info.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.