前言
事情是这样的, 我最近在开发一个 uniapp APP 端项目, 里面有一个模拟请求的代码, 需要使用到定时器
但是,我发现在 定时器中 普通函数 无法通过 this.message 获取数据
按照经验,把它改成 箭头函数 就可以解决
下面我来带大家复习一下有关于 Vue 中 内置的 this 等等相关知识
建议
如果对 JS 的 this 没有概念的,建议前去学习再来往下看.过几天,我也总结一下,JS 中的 this
开始
列子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Vue.js Example with Methods</title>
<!-- 引入Vue.js库 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
</head>
<body>
<div id="app">
<h1>{{ message }}</h1>
<button @click="generate_profile">普通函数</button>
<button @click="generate_profile2">箭头函数</button>
</div>
<script>
new Vue({
el: "#app",
data: {
message: "Hello Vue with Methods!",
counter: 0,
},
methods: {
generate_profile() {
setTimeout(function () {
console.log("普通函数");
console.log(this);
console.log(this.message);
}, 0);
console.log("start");
},
generate_profile2() {
setTimeout(() => {
console.log("箭头函数");
console.log(this);
console.log(this.message);
}, 0);
console.log("start");
},
},
});
</script>
</body>
</html>
打印结果
在 Vue 中,如果你在组件的方法中定义了一个普通的回调函数
并将其传递给一个定时器(例如 setTimeout
或 setInterval
),
这个回调函数的 this
并不会自动绑定到 Vue 实例。
相反,它会遵循 JavaScript 中的常规规则,
即在非严格模式下指向全局对象(在浏览器中是 window
),在严格模式下是 undefined
。
这里有一个示例来说明这一点:
new Vue({
el: '#app',
data: {
message: 'Hello, Vue!'
},
mounted: function() {
var self = this; // 保存对 Vue 实例的引用
setTimeout(function() {
console.log(this); // 在非严格模式下指向 window,在严格模式下是 undefined
console.log(self.message); // 正确地访问 Vue 实例的数据
}, 1000);
}
});
在这个例子中,setTimeout
回调中的 this
并不指向 Vue 实例,
而是指向全局对象(或在严格模式下是 undefined
)。
为了能够在回调函数中访问 Vue 实例,
我们通常使用一个变量(如 self
)来保存对 Vue 实例的引用,
然后在回调中使用这个变量。
另一种方法是使用箭头函数作为定时器的回调,这样 this
就会捕获其所在上下文的 this
值:
new Vue({
el: '#app',
data: {
message: 'Hello, Vue!'
},
mounted: function() {
setTimeout(() => {
console.log(this.message); // 正确地访问 Vue 实例的数据
}, 1000);
}
});
使用箭头函数,this
将指向 mounted
方法的上下文,
也就是 Vue 实例本身。
这样你就可以直接访问 Vue 实例的属性和方法了。
联系
在 javascript 中,
对一个按钮添加点击事件,
点击触发函数时,
函数里面的this 指向的是这个按钮实例
而在 Vue 中
通过 @click 方式绑定事件
函数里面的this指向的Vue实例
在 指向 Vue 实例 情况下
才可以通过 this.变量 方式获取值
例子
在 Vue 中,当你在模板中使用 @click
指令绑定点击事件时,
该事件处理函数的 this
会指向绑定该事件的 Vue 实例。
这是因为 Vue 在内部自动将事件处理函数绑定到 Vue 实例上。
例如:
<template>
<div id="app">
<button @click="handleClick">点击我</button>
</div>
</template>
<script>
new Vue({
el: '#app',
methods: {
handleClick: function() {
console.log(this); // 指向 Vue 实例
}
}
});
</script>
在这个例子中,当按钮被点击时,handleClick
方法将被调用,
并且 this
将指向创建的 Vue 实例。
这意味着你可以访问 Vue 实例的数据、方法和其他属性。
如果你需要在事件处理函数中访问原生 DOM 元素,你可以使用 $refs
。例如:
<template>
<div id="app">
<button ref="myButton" @click="handleClick">点击我</button>
</div>
</template>
<script>
new Vue({
el: '#app',
methods: {
handleClick: function() {
console.log(this.$refs.myButton); // 获取按钮的 DOM 元素
}
}
});
</script>
在这个例子中,this.$refs.myButton
将指向绑定了 ref="myButton"
的按钮 DOM 元素。
总的来说,在 Vue 的点击事件处理函数中,
this
指向的是 Vue 实例本身,
这使得你可以方便地访问实例的所有属性和方法。