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

Vue:将道具从路由器传递到变量组件[duplicate]

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

    Vue.js .

    this lifecycle hooks ( created , mounted updated 等等)它的计算结果是 undefined

    mounted: () => {
      console.log(this); // logs "undefined"
    },
    

    同样的事情也发生在我的计算属性中:

    computed: {
      foo: () => { 
        return this.bar + 1; 
      } 
    }
    

    我得到以下错误:

    Uncaught TypeError:无法读取未定义的属性“bar”

    未定义 在这种情况下?

    0 回复  |  直到 8 年前
        1
  •  128
  •   Graham francescalus    8 年前

    这两个示例都使用 arrow function () => { } ,绑定 this 与Vue实例不同的上下文。

    根据 documentation

    vm.$watch('a', newVal => this.myMethod()) ). 由于箭头函数绑定到父上下文, this.myMethod 将未定义。

    为了得到正确的参考 作为Vue实例,请使用常规函数:

    mounted: function () {
      console.log(this);
    }
    

    或者,也可以使用 ECMAScript 5 shorthand 对于函数:

    mounted() {
      console.log(this);
    }
    
        2
  •  12
  •   Ashutosh Narang    7 年前

    arrow functions

    这个 Vue Documentation

    this . 相反, 在词汇上是绑定的(即。 它的意思与它原来的上下文保持一致)。

    var instance = new  Vue({
        el:'#instance',
      data:{
        valueOfThis:null
      },
      created: ()=>{
        console.log(this)
      }
    });
    

    Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}

    鉴于。。。如果我们使用正则函数(应该在Vue实例上使用)

    var instance = new  Vue({
        el:'#instance',
      data:{
        valueOfThis:null
      },
      created: function(){
        console.log(this)
      }
    });
    

    在控制台中记录以下对象:

    hn {_uid: 0, _isVue: true, $options: {…}, _renderProxy: hn, _self: hn, …}

    推荐文章