dwalsh
dwalsh

Reputation: 145

Issue with props and v-bind in VueJS

This may be a simple fix but I am not from a javascript background and am learning on the fly pretty much. So props and all that jazz isn't something I am fully understanding (yet!).

I want to display a specific key:value pair from this array:

health: [{ playerHealth: 100}, {monsterHealth: 100}]

this short piece of code is found in the data() section of App.vue with export default as follows:

data() {
return {
  health: [{
    playerHealth: 100
  }, {
    monsterHealth:100
  }]

It is passed into the component "health" as follows:

<health :health="health"></health>

In health.vue I am trying to display the playerHealth value, the way I am attempting this what follows in the template:

<div> {{health.playerHealth}} </div>

My export section is this:

export default {

props:['health'], name:"Health"

However I am getting nothing displayed. What I can display however is simply just {{health}}. That returns the full array. Am I accessing the values incorrectly?

Any help would be appreciated I am aware it may be a simple thing but I haven't found an answer.

If you require full code of each vue file please let me know.

Upvotes: 0

Views: 1203

Answers (2)

Aleksander Pentchev
Aleksander Pentchev

Reputation: 1

Since "health" is an array you cannot access items via dot notation which works for objects, not arrays.

You could use computed properties as shown before. Or you could also try like this:

health[0].playerHealth 

Simply put, you reach to a certain element in the array which is an object and then via dot notation access it's property. But I would rather go for computed properties to make your code cleaner and because their are designed to output transformed data based on props, for instance.

Upvotes: 0

Ohgodwhy
Ohgodwhy

Reputation: 50787

health is actually an array that contains n objects. In your case, a computed property will be helpful for you

<health :health="health"></health>

This is fine, now within that component, define a computed method that will give you the real health from the array:

computed: {
  playerHealth() {
    return this.health[0].playerHealth
  }
}

And you can use it in mustache syntax, or you can use v-text:

<div v-text="playerHealth"></div>
<div> {{ playerHealth }} </div>

Upvotes: 1

Related Questions