我遇到的一些问题(2019.4.28)
声明:本人还是一个大三小白,有错误请谅解。
一、setInterval和setTImeout会导致与 this 绑定到全局对象运行
var app = new Vue({
el: '#app',
data: {
msg: '不要管',
date: new Date(),
name: 'huahua',
age: '<p>28</p>',
change: 'red',
number: 1000
},
methods: {
count: function() {
console.log(this)
this.number += 1
}
},
filters: {
filter: function() {
let date = new Date()
let year = date.getFullYear()
let month = date.getMonth() + 1
let day = date.getDay()
let sec = date.getSeconds()
return year + '-' + month + '-' + day + '-' + sec
}
},
mounted: function() {
//注意setInterval中的this指向
setInterval(function(){
this.date = new Date() //错误!
}, 1000)
}
})
在这段代码中,this指向window
改正: (让this指向vue实例)
(1)借助变量保存this
mounted: function() {
//注意setInterval中的this指向
let _this = this
setInterval(function(){
_this.date = new Date() //错误!
}, 1000)
}
(2)利用箭头函数
使用es6中的箭头函数,因为在箭头函数中this是固定的。
箭头函数可以让setTimeout里面的this,绑定定义时所在的作用域,而不是指向运行时所在的作用域。
mounted: function() {
//注意setInterval中的this指向
setInterval(()=>{
this.date = new Date() //错误!
}, 1000)
}
二、ASCII码 转换问题
// char-->ascii
var a = 122;
console.log("a".charCodeAt(0));
// ascii-->char
String.fromCharCode(a);
三、getYear()和getFullYear()
之前以为获取完整年是getYear(),发现错了,getYear是1900开始的
new Date().getYear(); //116
new Date().getFullYear(); //2016