【问题标题】:Object methods in vue js datavue js数据中的对象方法
【发布时间】:2018-12-12 20:38:36
【问题描述】:

我正在尝试用 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;
    }
}
});

action 方法不起作用,我试过用这个关键字和双引号,也不起作用。在 html 中,我通过以下方式调用:

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

另一个问题是数量,我希望函数动作会减少数量,但我不能引用那个对象。谢谢!

【问题讨论】:

标签: javascript oop dom vue.js vuejs2


【解决方案1】:

避免使用.find 并制作你的数组和对象

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

要访问药水操作:

inventory.potion

【讨论】:

    【解决方案2】:

    你可以尝试调用action

    <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>
    

    【讨论】:

    • 是的,但仍然无法正常工作。我认为错误在函数中,我不太清楚要返回什么
    • @RaúlS 添加方法 action() { this.findItem().action() } 并在点击事件中调用它,如@click="action"。并添加代码 this.playerHealth = this.playerHealth + 25; this.amount++;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2019-12-04
    • 2019-09-08
    • 2018-10-30
    • 2015-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多