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

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.

主站蜘蛛池模板: 富宁县| 大竹县| 塘沽区| 虎林市| 宁津县| 常德市| 大英县| 阳信县| 确山县| 乐平市| 江山市| 肇源县| 丁青县| 田阳县| 商洛市| 河西区| 永平县| 南京市| 德昌县| 富裕县| 江门市| 河北区| 舟山市| 修文县| 芮城县| 芦溪县| 永平县| 越西县| 交口县| 绥芬河市| 镇远县| 楚雄市| 临猗县| 沧州市| 潜山县| 柘荣县| 东阳市| 盘山县| 九龙城区| 乌兰浩特市| 成都市|