vue简易上下移动,遇到墙的问题,求解答

71 阅读1分钟

vue简易上下移动案例,遇到墙不能走,怎么判断在多个墙的上下左右不能移动,只会写一个墙的情况,求大佬解答

`

<div id="app">
    <div class="content">
        <div class="xz" :style="{left:leftVal + 'px',top:topVal + 'px'}">

        </div>
        <div class="qb" :style="{left:leftValue + 'px',top:topValue + 'px'}">

        </div>
        
    </div>
    <div>
        <h1>leftVal:{{leftVal}}</h1>
        <h1>topVal:{{topVal}}</h1>
    </div>
</div>
<script>
    new Vue({
        el: '#app',
        data: {
            leftVal: 0,
            topVal: 0,
            leftValue: 300,
            topValue: 200,
        },
        methods: {
            move(event) {
                switch (event.keyCode) {
                    case 37:
                        if (this.leftVal < 100 || (this.leftVal == this.leftValue+100 && this.topVal == this.topValue+100)) {
                            this.leftVal = this.leftVal
                            alert('左边有墙');
                            console.log(this.leftValue[0]);
                        } else {
                            this.leftVal -= 100;
                        }
                        break;
                    case 38:
                        if (this.topVal < 100 || (this.leftVal == this.leftValue && this.topVal == this.topValue+200)) {
                            this.topVal = this.topVal
                            alert('上边有墙')
                        } else {
                            this.topVal -= 100;
                        }
                        break;
                    case 39:
                        if (this.leftVal >= 700 || (this.leftVal == this.leftValue-100 && this.topVal == this.topValue+100)) {
                            this.leftVal = this.leftVal
                            alert('右边有墙')
                        } else {
                            this.leftVal += 100;
                        }
                        break;
                    case 40:
                        if (this.topVal >= 700 || (this.leftVal == this.leftValue    && this.topVal == this.topValue)) {
                            alert('下边有墙')
                            this.topVal = this.topVal
                        } else {
                            this.topVal += 100;
                        }
                        break;
                    default:
                        break;
                }
            }
        },
        mounted() {
            document.addEventListener('keydown', this.move)
        },
    })
</script>
`

微信图片_20230510162442.png