理解Vue中的'this'关键字 [英] Understanding the 'this' keyword in Vue

查看:28
本文介绍了理解Vue中的'this'关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从头开始学习 VueJS.我正在关注他们的官方指南.但我被困在这里:https://vuejs.org/v2/guide/#Handling-用户输入

在这个例子中...

var app5 = new Vue({el: '#app-5',数据: {消息:你好 Vue.js!"},方法: {反向消息:函数(){this.message = this.message.split('').reverse().join('')}}})

..如何直接访问 message 属性而不引用 data 对象?如果 this 关键字引用当前 Vue 实例,不应该像这样访问 message 属性:this.data.message?

考虑以下示例:

<代码>({name: "John Doe",数据: {消息:你好世界"},问候:函数(){console.log("我是" + this.name);console.log("我有一条消息给你:" + this.data.message);//看这里}}).迎接();

这就是我在 vanilla javascript 中访问属性的方式.有人可以让我了解幕后发生的事情吗?

解决方案

在 Vue 中,Vue 实例使用 代理

I have started to learn VueJS from scratch. I am following their official Guide. But I am stuck here: https://vuejs.org/v2/guide/#Handling-User-Input

In this example...

var app5 = new Vue({
  el: '#app-5',
  data: {
    message: 'Hello Vue.js!'
  },
  methods: {
    reverseMessage: function () {
      this.message = this.message.split('').reverse().join('')
    }
  }
})

..how is it that the message property is directly being accessed without any reference to the data object? If this keyword refers to the current Vue instance, shouldn't the message property be accessed like this: this.data.message?

Consider the following example:

({
  name: "John Doe",
  data: {
    message: "Hello World"
  },
  greet: function(){
    console.log("I am " + this.name);
    console.log("I have a message for you: " + this.data.message); //see here
  }
}).greet();

This is how I would have accessed a property in vanilla javascript. Can someone please make me understand what's going on behind the scenes?

解决方案

In Vue, Vue instance proxy properties of data and methods by using Proxy

这篇关于理解Vue中的'this'关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆