代码之家  ›  专栏  ›  技术社区  ›  Johnson

处理VueJS范围

  •  0
  • Johnson  · 技术社区  · 7 年前

    我正在处理一个范围问题,无法使用变通方法 let that = this; 我想改变变量 error . 给你一个 CODEPEN Example

    HTML格式

    <div id="app" class="container">   
        {{error}}
        <br>
        <button type="button" @click="change()">Change Variable Error</button>
    </div>
    

    var demo = new Vue({
        el: '#demo',
    
        data:{
          error: "a",
          item: {
            foo: function(){
                alert('Change!');
              this.error = "Something went wrong!";
            }
        }
        },
        methods:{
            change(){
            this.item.foo();
          }
        }
    });
    

    谢谢!

    1 回复  |  直到 7 年前
        1
  •  1
  •   Jae Woo Woo    7 年前

    这不是vue的问题,而是javascript的“这个”问题。您可以在方法中使用此代码获得所需的内容。

    change() {
        this.item.foo.bind(this)();
    }
    

    在函数foo中,有 this.error this 未绑定到vue实例的范围。所以,在调用之前,应该将它绑定到这个作用域上。