Vue3 使用 ref 和 reactive 控制 div 上下左右移动
在 Vue 3 中,可以通过使用ref和reactive来控制div的上下左右移动。下面是一个示例代码:
首先,需要在Vue组件的setup方法中创建需要移动的div的引用和位置信息:
import { ref, reactive } from 'vue';
export default {
setup() {
// 创建div的引用
const divRef = ref(null);
// 创建位置信息
const position = reactive({
top: 0,
left: 0,
});
return {
divRef,
position,
};
},
};
然后,在模板中使用divRef引用div,并通过style绑定top和left样式属性来实现移动:
<template>
<div
ref="divRef"
:style="{ top: `${position.top}px`, left: `${position.left}px` }"
class="movable-div"
>
<!-- div内容 -->
</div>
</template>
接下来,可以在组件的methods中定义移动div的方法,例如:
methods: {
moveDiv(direction) {
switch (direction) {
case 'up':
this.position.top -= 10;
break;
case 'down':
this.position.top += 10;
break;
case 'left':
this.position.left -= 10;
break;
case 'right':
this.position.left += 10;
break;
default:
break;
}
},
},
最后,在模板中添加按钮或其他触发事件的元素,并调用移动方法:
<template>
<div>
<button @click="moveDiv('up')">向上移动</button>
<button @click="moveDiv('down')">向下移动</button>
<button @click="moveDiv('left')">向左移动</button>
<button @click="moveDiv('right')">向右移动</button>
<div
ref="divRef"
:style="{ top: `${position.top}px`, left: `${position.left}px` }"
class="movable-div"
>
<!-- div内容 -->
</div>
</div>
</template>
这样就可以通过点击按钮来控制div的上下左右移动了。注意,需要在样式中设置.movable-div的position属性为absolute或fixed,以便使div的位置属性生效。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/pi2x 著作权归作者所有。请勿转载和采集!