vue js数据中的对象方法

时间:2018-07-04 11:54:50

标签: javascript oop dom vue.js vuejs2

我正在尝试使用Vuejs做一些小游戏。问题是我想要一个清单,并向其中添加对象。每个对象都必须有自己的动作,例如药水可以治愈。因此,我尝试执行以下操作,但是我认为Vue无法做到这一点,但是我没有找到解决方案。

new Vue({
el: '#app',
data: {
    playerHealth: 100,
    enemyHealth: 100,
    invClicked: false,
    gameStarted: false,
    logs: [],
    specialAttacks: [],
    inventory: {
        potion: {
            amount: 1,
            img: 'images/potion.svg',
            action: function(){
                this.playerHealth = this.playerHealth + 25;
            }
        }
    }
},
computed: {
    eHealthColor: function() {
        if (this.enemyHealth < 25){
            return 'red';
        }
    },
    pHealthColor: function() {
        if (this.playerHealth < 25){
            return 'red';
        }
    },
    numberOfPlayers: function() {
        return 2;
    }
},
methods: {
    attack: function(event) {
        let dealedDamage = (Math.floor(Math.random() * (5 - 1)) + 1);
        let damageTaken = (Math.floor(Math.random() * (3 - 1)) + 1);

        if(this.enemyHealth > dealedDamage){
            this.enemyHealth = this.enemyHealth - dealedDamage;
            this.logs.unshift(`PLAYER HITS ENEMY FOR ${dealedDamage}`);
        } else {
            this.enemyHealth = 0;
            alert('YOU WON!')
        }

        if(this.playerHealth > damageTaken){
            this.playerHealth = this.playerHealth - damageTaken;
            this.logs.unshift(`ENEMY HITS PLAYER FOR ${damageTaken}`);
        } else{
            this.playerHealth = 0;
            alert('YOU LOST!');
        }
    },
    findItem: function() {
        var item = this.inventory.potion;
        return item;
    }
}
});

该操作方法不起作用,我尝试使用此关键字并用双引号引起来,但也不起作用。在html中,我的致电方式是:

<div class="inv-item position-relative d-flex justify-content-center" @click="findItem().action">

另一个问题是数量,我希望函数操作可以减少数量,但是我不能引用该对象。谢谢!

2 个答案:

答案 0 :(得分:0)

避免使用.find并创建数组和对象

inventory: {
  'potion': {
    ...
  }
}

要访问药水动作,请执行以下操作:

inventory.potion

答案 1 :(得分:0)

您可以尝试调用操作

<div class="inv-item position-relative d-flex justify-content-center" @click="findItem().action()">Action</div>

或直接使用对象:

<div class="inv-item position-relative d-flex justify-content-center" @click="inventory.potion.action">Action</div>