vue实现画板

420 阅读1分钟

我正在参加「码上掘金挑战赛」详情请看:码上掘金挑战赛来了!

项目效果

项目实现

html

  • @mouseover 鼠标经过事件,@dblclick 双击事件
  • 其他都是一些常用标签
  <div class="mouse-container">
    <!-- 左边绘色区域 -->
    <div class="box">
        <span v-for="(item, i) in list" :key="i"
        :class="{'active': item.show}"
        @mouseover="mouseoverFn(i)"
        @click="clickFn(i)"
        @dblclick="dblclickFn(i)"></span>
    </div>
    <!-- 右边描述区域 -->
    <div class="description">
        <span>{{text}}</span>
        <button @click="clickBtnFn">切换</button><br><br>
        <span>双击取消绘色</span><br>
        <button @click="clickEmptyFn">清空</button>
    </div>
  </div>

script

  • forEach()  方法就是对数组的每个元素执行一次给定的函数,是js内置的数组方法,可以直接用。
  • 提示都写在代码旁边,逻辑都很简单
data () {
    return {
      list: [],
      text: '鼠标经过绘色'
    }
  },
  created () { // 准备数据
    for (let i = 1; i <= 100; i++) {
      const obj = {
        id: i,
        show: false
      }
      this.list.push(obj)
    }
  },
  methods: {
    // 封装函数
    _edit (i, state) {
      this.list.forEach(item => {
        if (item.id === i + 1) {
          item.show = state
        }
      })
    },
    // 鼠标经过小盒子
    mouseoverFn (index) {
      if (this.text !== '鼠标经过绘色') return
      this._edit(index, true) // 鼠标经过显示颜色
    },
    // 鼠标点击小盒子
    clickFn (index) {
      if (this.text !== '鼠标点击绘色') return
      this._edit(index, true) // 鼠标点击显示颜色
    },
    // 鼠标双击小盒子
    dblclickFn (index) {
      this._edit(index, false) // 鼠标双击取消显示颜色
    },
    // 点击切换按钮
    clickBtnFn () {
      this.list.forEach(item => {
        item.show = false
      }) // 清空画板显示颜色
      if (this.text === '鼠标经过绘色') {
        this.text = '鼠标点击绘色' // 替换文字
      } else if (this.text === '鼠标点击绘色') {
        this.text = '鼠标经过绘色' // 替换文字
      }
    },
    // 点击清空按钮
    clickEmptyFn () {
      this.list.forEach(item => {
        item.show = false
      }) // 清空画板显示颜色
    }
  }

css

  • cursor:pointer属性是在计算机中将鼠标指针变为小手
  • 只用了弹性布局,其他都是一些常用的css样式
.active{
    background: red!important; // 注意权重
}
body{
  background: #1a232e; // 背景色
}
.mouse-container{
    display: flex;
    width: 600px;
    margin: auto;
    color: #fff;
    .box{
        display: flex;
        width: 240px;
        margin-right: 80px;
        justify-content: space-around;
        flex-wrap: wrap;
        span{
            width: 20px;
            height: 20px;
            background: #beb9b9;
            margin: 2px;
        }
    }
    button{
        padding: 5px;
        margin: 10px;
        background: pink;
        border: 1px solid #000;
        border-radius: 10px;
        cursor: pointer;
    }
}