【问题标题】:Why to reference the this variable to modify the DOM elements? :Clarification on 'this' in Vue Component [duplicate]为什么要引用 this 变量来修改 DOM 元素? :澄清 Vue 组件中的“this”[重复]
【发布时间】:2018-05-30 19:17:19
【问题描述】:

我有一个具有以下结构的 vue 组件:

   export default{
     name: '',
     data: function () {
        return {
           var1 :{},
           var2 : {},
           ...
        }
     },
     created: function () {
         this.methodName1()
     },
     methods: {
        methodName2: function () {
           var context = this

           rp(options).then(function () {
              context.methodName1()
              return null
           }).catch(function (err) {
              console.log(err)
           })
       },
       methodName1: function () {
             //function body
       }
   }

我的疑问是为什么this.methodName1 给出 undefined where as

    var context = this; 
    context.methodName1 

在 methodName2 中工作得很好吗?

为什么我们需要引用 this 变量来修改 DOM 元素?

【问题讨论】:

  • 是你的问题,为什么你不能在methodName2的then回调中写this.methodName1()
  • 是的,不仅在回调外也回调
  • VueJS 为methods 牵着你的手,将他们的this 重新连接成更复杂的对象。但它不会对方法内的代码执行此操作。您将使用胖箭头函数 - 或显式存储上下文,就像您在那个 sn-p 中所做的那样。
  • 好的。我明白了一点,但我的困惑仍然在于 1。为什么我们将对此的引用存储在另一个变量中? 2.为什么直接使用this不起作用? (var context = this; context.methodName1this.methodName1()不一样)

标签: javascript vue.js scope this


【解决方案1】:

仔细查看官方文档中的Lifecycle-Diagram。您正在尝试在 created 中运行 this.methodName1(),它在您的 methods 之前被挂钩,这意味着您正在尝试运行尚未附加的方法。
mounted 是您所有方法所在的位置已经可用。
变化:

created: function () {
     this.methodName1()
},

mounted: function () {
     this.methodName1()
},

你应该很高兴。

【讨论】:

  • created 钩子可以用于访问方法和组件数据,mounted 是必要的,如果您想访问 DOM 或操作子组件。你的答案不正确。
猜你喜欢
  • 2018-10-01
  • 1970-01-01
  • 2011-01-20
  • 1970-01-01
  • 1970-01-01
  • 2014-07-31
  • 2020-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多