vue2实现在屏幕中有一个小机器人可以随意移动

第一步:创建store目录结构

复制代码
src/
├── store/
│   ├── modules/
│   │   └── robot.js     # 机器人专用状态模块
│   └── index.js         # Vuex 主配置文件

第二步:创建机器人状态模块

创建 src/store/modules/robot.js 文件,内容如下:

复制代码
// 从本地存储读取初始位置(实现持久化)
const getInitialPosition = () => {
    try {
      return JSON.parse(localStorage.getItem('robotPosition')) || { x: 100, y: 100 }
    } catch {
      return { x: 100, y: 100 }
    }
  }
  
  export default {
    namespaced: true,  // 启用命名空间
    
    state: () => ({
      position: getInitialPosition(),
      visibility: true
    }),
    
    mutations: {
      UPDATE_POSITION(state, newPos) {
        state.position = newPos
        // 同步到本地存储
        localStorage.setItem('robotPosition', JSON.stringify(newPos))
      },
      TOGGLE_VISIBILITY(state) {
        state.visibility = !state.visibility
      }
    },
    
    actions: {
      setPosition({ commit }, position) {
        commit('UPDATE_POSITION', position)
      },
      resetPosition({ commit }) {
        commit('UPDATE_POSITION', getInitialPosition())
      }
    },
    
    getters: {
      formattedPosition: state => {
        return `X: ${state.position.x}px, Y: ${state.position.y}px`
      }
    }
  }

第三步:配置主Store文件

修改 src/store/index.js:

复制代码
import Vue from 'vue'
import Vuex from 'vuex'
import robot from './modules/robot'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    robot  // 注册机器人模块
  }
})

第四步:初始化Vuex

在 main.js 中挂载 store:

复制代码
import Vue from 'vue'
import App from './App.vue'
import store from './store'  // 自动识别 index.js

new Vue({
  store,  // 注入全局 store
  render: h => h(App)
}).$mount('#app')

第五步(可选):增强持久化配置

如果要实现更复杂的持久化,可以使用 vuex-persistedstate:

1.安装插件:

复制代码
npm install vuex-persistedstate

2.修改 store 配置:

复制代码
// store/index.js
import createPersistedState from 'vuex-persistedstate'

export default new Vuex.Store({
  modules: { /*...*/ },
  plugins: [
    createPersistedState({
      paths: ['robot.position']  // 只持久化位置信息
    })
  ]
})

第六步:创建全局机器人组件(components/GlobalRobot.vue)

复制代码
<template>
  <div class="global-robot" :style="robotStyle" @mousedown="startDrag" @click="opendialog">
 🤖
  
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'

export default {

  name: 'GlobalRobot',
  data() {
    return {

      isDragging: false,
      dragOffset: { x: 0, y: 0 },
      elementWidth: '',
      elementHeight: ''
    }
  },
  computed: {
    ...mapState('robot', ['position']),
    robotStyle() {
      return {
        left: `${this.position.x}px`,
        top: `${this.position.y}px`,
        zIndex: 9999
      }
    }
  },
  methods: {
    ...mapActions('robot', ['setPosition']),

    startDrag(e) {
      this.isDragging = true
      const rect = this.$el.getBoundingClientRect()
      this.elementWidth = rect.width
      this.elementHeight = rect.height
      console.log(this.elementWidth)
      console.log(this.elementHeight)
      this.dragOffset = {
        x: e.clientX - this.position.x,
        y: e.clientY - this.position.y
      }

      document.addEventListener('mousemove', this.onDrag)
      document.addEventListener('mouseup', this.stopDrag)
      e.preventDefault()
    },

    onDrag(e) {
      if (!this.isDragging) return
      const maxX = window.innerWidth - this.elementWidth
      const maxY = window.innerHeight - this.elementHeight
      const newX = e.clientX - this.dragOffset.x
      const newY = e.clientY - this.dragOffset.y
      // 严格边界限制
      this.setPosition({
        x: Math.max(0, Math.min(newX, maxX)),
        y: Math.max(0, Math.min(newY, maxY))
      })
      console.log(
  `边界检测: 
  newX=${newX}, 
  maxX=${maxX}, 
  clampedX=${Math.max(0, Math.min(newX, maxX))}`
)
      
    },

    stopDrag() {
      this.isDragging = false
      document.removeEventListener('mousemove', this.onDrag)
      document.removeEventListener('mouseup', this.stopDrag)
    },
    opendialog() {
      this.dialogVisible = true
    }
  }
}
</script>

<style scoped>
.global-robot {
  position: fixed;
  width: 100px;
  height: 100px;
  /* background-image: linear-gradient(92deg, #407cd6 15%, #3ebcb4 48.8525390625%, #397ace 100%); */
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 50px;
  cursor: move;
  user-select: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  transition:
    transform 0.2s,
    box-shadow 0.2s;
  pointer-events: auto;
  /* 确保可交互 */
}

.global-robot:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.25);
}

.global-robot:active {
  cursor: grabbing;
  transform: scale(0.95);
}
</style>
相关推荐
crazyme_69 分钟前
前端自学入门:HTML 基础详解与学习路线指引
前端·学习·html
撸猫79117 分钟前
HttpSession 的运行原理
前端·后端·cookie·httpsession
亦世凡华、36 分钟前
Rollup入门与进阶:为现代Web应用构建超小的打包文件
前端·经验分享·rollup·配置项目·前端分享
Bl_a_ck1 小时前
【React】Craco 简介
开发语言·前端·react.js·typescript·前端框架
为美好的生活献上中指1 小时前
java每日精进 5.11【WebSocket】
java·javascript·css·网络·sql·websocket·网络协议
augenstern4162 小时前
webpack重构优化
前端·webpack·重构
海拥✘2 小时前
CodeBuddy终极测评:中国版Cursor的开发革命(含安装指南+HTML游戏实战)
前端·游戏·html
寧笙(Lycode)3 小时前
React系列——HOC高阶组件的封装与使用
前端·react.js·前端框架
asqq83 小时前
CSS 中的 ::before 和 ::after 伪元素
前端·css
拖孩3 小时前
【Nova UI】十五、打造组件库之滚动条组件(上):滚动条组件的起步与进阶
前端·javascript·css·vue.js·ui组件库