2021年4月开发问题汇总

Aditya2021-05-19开发问题

2021年4月开发问题汇总

  1. js一个元素从DOM中被删除后,他所绑定的事件浏览器是如何处理的?
  2. git 恢复之前版本
  3. 获取图片实际宽高
  4. npm/pm2 command not found
  5. watch监听到新值旧值一样问题
  6. Git fatal: Could not read from remote repository Solution

1. js一个元素从DOM中被删除后,他所绑定的事件浏览器是如何处理的?

let audioEle = document.createElement('audio')
audioEle.src = "/static/audio/voice.mp3"
document.body.append(audioEle)
audioEle.play()
audioEle.addEventListener("ended", function() {
  document.body.removeChild(audioEle)
});

是否需要给绑定事件解绑?

第一次实验DOM删除
let audioEle = document.createElement('audio')
audioEle.src = "/static/audio/voice.mp3"
document.body.append(audioEle)
audioEle.play()
audioEle.addEventListener("ended", function() {
  document.body.removeChild(audioEle)
  document.body.append(audioEle)
  audioEle.play()
});

给 audioEle 添加了事件之后再删除,再恢复回来,事件依然有效。

试验结论:span 从 DOM 中删除了,但是对象还在啊,它的属性、事件这些都还在啊,所以再加回 DOM,仍然有效。

对象置为null

引用

使用Node.removeChild(element)ChildNode.remove()并不会直接释放对应的event listener,但是会被gc。如果该dom对象在js中再无其他引用,与之绑定的event listener就会在合理的时机被gc。

如果被remove的dom对象没有其他引用,你并不需要手动解绑事件

element = document.getElementById("xxx");
element.remove();
element = null;  // 对该dom对象的引用数变为0,gc会适时回收该dom对象上的所有event listener

2. git 恢复之前版本

gi t reset

git reset --hard 版本号
git push -f // 提交更改

3. 获取图片实际宽高

// 图片地址
const img_url = window.createObjectUrl(file)

// 创建对象
const img = new Image()

// 改变图片的src
img.src = img_url

// 判断是否有缓存
if(img.complete){
    // 打印
    alert('from:complete : width:'+img.width+',height:'+img.height)
}else{
    // 加载完成执行
    img.onload = function(){
        // 打印
        alert('width:'+img.width+',height:'+img.height)
    }
}

4. npm/pm2 command not found

这个提示是找不到npm 跟pm2 命令, 但是我们在服务器上使用 npm -v pm2 -v 是可以查看到版本好的, 也就是安装好的

这个时候提示 command not found 是因为在自动部署的时候 使用的全局下的npm pm2 命令,在全局环境下 找不到这两个命令, 自然就报错了

为了验证, 可以执行 sudo npm -v sudo pm2 -v 也会提示 command not found

为了解决这个问题需要让npm pm2 建立软连接,相当于放在环境变量中

首先查看 npm 的安装位置

可以使用 whereis npm 查看npm 的安装路径, 如果 whereis npm 显示路径为空,

则使用 which npm 比如 这里显示的路径是 /usr/local/src/node-v10.16.3-linux-x64/bin/npm

然后执行

sudo ln -s  /usr/local/src/node-v10.16.3-linux-x64/bin/npm  /usr/bin/npm

这就相当于把npm 链接到了 全局环境变量中

这时候在执行 sudo npm -v 就不报错了

5. watch监听到新值旧值一样问题

注意:当变更(不是替换)对象或数组并使用 deep 选项时,旧值将与新值相同,因为它们的引用指向同一个对象/数组。Vue 不会保留变更之前值的副本。

解决这个问题取巧就是设置一个计算属性,保存数据的副本,然后监听这个副本的变化

watch: {
    messageData(newVal,oldVal) {
        console.log("newVal");
        console.log(newVal);
        console.log("oldVal");
        console.log(oldVal);
    },
    deep: true
},
computed: {
    messageData() {
        return Json.parse(JSON.stringify(xxx))
    }
}

6. Git fatal: Could not read from remote repository Solution

kex_exchange_identification: read: Connection reset by peer
fatal: Could not read from remote repository.

拉取gitlab代码的时候突然报错,网上大部分信息都是针对ssh keygen的设置,

由于我之前已经设置了并且github也正常使用,所以也就没有重置ssh key。

验证git的方式有两种一种是ssh,另一种是http方式,如果出现这种情况直接使用

git remote set-url http://gitlab.xxx.com/xx.git

完美解决

参考

Last Updated 2024/12/27 11:36:49