ToddT
ToddT

Reputation: 3258

Vue - use computed property inside HTML data

How can I use the return value of a computed property inside a data element that is rendered as HTML?

I have a data element that is HTML, and it looks like this:

contractContent: `<p>Hi ${this.brideName},</p>`

I've also tried this:

contractContent: `<p>Hi {{this.brideName}},</p>`

I am trying to pass in the name via this computed property:

brideName() {
  return this.returnContracts[0].brideName.split(' ')[0]
},

But all I'm getting is undefined. If I just put brideName on the component as a test, it returns the first name of the bride just fine.

Where did I go astray?

Here is a fiddle with my dilemma

Upvotes: 1

Views: 2648

Answers (2)

tony19
tony19

Reputation: 138696

data() is invoked on component creation and is not reactive. contractContent should be a computed prop for your code to work:

export default {
  data() {
    return {
      name: "Martina Navratilova",
    }
  },
  computed: {
    brideName() {
      return `<p>Hi ${this.name.split(' ')[0]},</p>`
    },
    contractContent() {
      return `<p>Hi there ${this.brideName}</p>`
    },
  },
}

updated fiddle

Upvotes: 1

Suraj Tiwari
Suraj Tiwari

Reputation: 386

Instead of going with data -> computed -> data -> render, go directly with computed -> render (html)

In your template you can render html like this

 <span v-html="brideName" />

assuming your data structure of returnContracts to be like this

data: {
  returnContracts: [
    {
      "brideName": "Emma Watson"
    }
  ]
}

Then you can directly render brideName from computed

brideName(){
  // assuming you'll have correct data, if data isn't valid this will cause crash.
  return `<p>Hi ${this.returnContracts[0].brideName.split(' ')[0]},</p>`
}

here is a fiddle to help you out implementation

Upvotes: 2

Related Questions