桌面版掘金系列连连看~摸鱼不如连连看~

769 阅读2分钟

我正在参与掘金创作者训练营第6期, 点击了解活动详情

通过本文,你可以得到一个桌面版的掘金主题连连看,正文马上开始,本文基于vue2.x+electron 欢迎各位掘友重构react版

前言

第一次我们初始化项目时可能需要翻墙,需要处理的步骤也比较多,因与本文主题相关性不强但又是前置必备条件,所以这里建议大家参考# 基于Electron+vue的跨平台实践初探 这篇文章,完成初始化后,可以正式尝试本文的下面内容

本地开发环境搭建

略,假设已经通过前言内的文章搭建好了项目,这里我的项目名称是 juejin-lianliankan

  • 设置窗口大小,这里我们获取了整个屏幕的宽高,然后设置了一下
import {screen} from 'electron'
 const primaryDisplay = screen.getPrimaryDisplay()
  width = primaryDisplay.workAreaSize.width
  height = primaryDisplay.workAreaSize.height
  // Create the browser window.
  win = new BrowserWindow({
    width: width / 5 * 4,
    height: height,
    ...
    })

image.png

页面布局

页面布局参考我的# 基于Jquery实现一个连连看小游戏,我赌你连普通级也过不去 这篇文章,本文基于vue去实现连连看的相关逻辑,并且将简陋的文字改为掘金系列主题。

设置掘金首发会员预约背景

background-image: url('https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/2dd2ce5ef03240c19c10fe79325983af~tplv-k3u1fbpfcp-no-mark:0:0:0:0.awebp');
background-size: 100%;
background-repeat: no-repeat;
background-color: #65a9fd;

image.png

连连jquery代码转为vue版

这里我们需要将全局变量转为data里的变量,函数转为methods,直接操作dom的我们需要通过动态类名,动态样式以及v-for循环进行实现

 <div
      class="box"
      id="box"
    >
      <div class="item" :style="comStyle" :x="item.x" :y="item.y" v-for="(item, index) in arr" :key="index"></div>
    </div>
     computed: {
    comStyle () {
      return {
        width: Math.sqrt((800 * 800) / (100 * this.level)) + 'px',
        height: Math.sqrt((800 * 800) / (100 * this.level)) + 'px'
      }
    }
  },

image.png

从掘金商城拿到图片素材

掘金商城的商品就是我们最好的连连看元素,这里将商品图片的地址转为数组,然后在生成元素时随机赋予背景图。

let imgSrc = ['https://img01.yzcdn.cn/upload_files/2022/03/16/Fl7X9CJjkJkexYEz8hjweZB1nc5v.png!280x280.jpg'...]
const inx = Math.ceil(Math.random() * imgSrc.length)
this.arr.push({ x, y: x, src: imgSrc[inx] })
this.arr.push({ x, y: x, src: imgSrc[inx] })

改写点击事件,实现连连看核心逻辑

添加点击事件

<div class="item" @click="itemClick(item)"

增加成功的变量和点击的变量

clickItem: [],
binGoItem: []

改写点击事件逻辑,动态添加类名和样式,这里为了保证全局唯一,为每一项元素引入一个nanoid属性,依赖 nanoid库生成

:class="[clickItem.includes(item.nanoid)?'transform':'']"
:style="{...comStyle, backgroundImage: (clickItem.includes(item.nanoid) || binGoItem.includes(item.nanoid)) ?`url(${item.src})`:''}"
itemClick ({ nanoid }) {
  if (!this.binGoItem.includes(nanoid)) {
    this.clickItem.push(nanoid)
  }
},

image.png 添加成功判断以及点击两次以上的判断

if (this.clickItem.length > 2) {
    this.clickItem = []
  }
  if (this.clickItem.length === 2) {
    if (this.clickItem[0] === this.clickItem[1]) {
      this.binGoItem.push(...this.clickItem)
      this.clickItem = []
    }
  }

以上就是掘金主题连连看jquery->vue的全部内容了,electron版的不知道怎么打包上传,现在将vue版以码上掘金的方式引入,通过本文以及之前jquery版的文章对比可以发现,基于vue数据驱动的明显代码更为简洁,而且关注点单一而集中,更容易写出好的代码,感谢大家的阅读,欢迎批评指正。