官术网_书友最值得收藏!

How Vue handles 'this'

You may have noticed up to this point that we're able to reference values inside of our data, methods, and other objects using this syntax, but the actual structure of our instance is this.data.propertyName or this.methods.methodName; all of this is possible due to the way Vue proxies our instance properties.

Let's take a very simple Vue application that has one instance. We have a data object that has a message variable and a method named showAlert; how does Vue know how to access our alert text with this.message?

<template>
<button @click="showAlert">
Show Alert</button>
</template>

<script>
export default {
data() {
return {
message: 'Hello World!',
};
},
methods: {
showAlert() {
alert(this.message);
},
},
};
</script>

Vue proxies the instance properties to the top level object, allowing us to access these properties via this. If we were to log out the instance to the console (with the help of Vue.js devtools), we'd get the following result:

Console logout

The key properties to look at within the preceding screenshot are message and showAlert, both of which are defined on our Vue instance yet proxied to the root object instance at initialization time.

主站蜘蛛池模板: 松江区| 郎溪县| 满洲里市| 靖州| 古田县| 台安县| 绵阳市| 饶阳县| 巢湖市| 平武县| 东兰县| 和静县| 新巴尔虎右旗| 冀州市| 建阳市| 吉安县| 亳州市| 淮南市| 含山县| 葫芦岛市| 德清县| 铜山县| 翁牛特旗| 庄河市| 浮山县| 定结县| 苍梧县| 汝阳县| 方城县| 上林县| 襄樊市| 诏安县| 灵石县| 治多县| 正阳县| 崇文区| 汝南县| 威宁| 仲巴县| 苏尼特右旗| 禹州市|