简体   繁体   中英

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.

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM