如何在vue组件默认prop函数中使用“this”

aka*_*kao 6 javascript vue.js vue-component vuejs2

export default {
  props: {
    goToSomePage: {
      type: Function,
      default: () => { this.$router.push({ name: 'some-page' }) }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我想做这样的事情,但“这个”未定义。

有什么办法可以解决这个问题吗?

我想给出一个默认操作并在回调函数中使用“this”。

小智 9

您可以将箭头函数更改为匿名函数,如下所示

export default {
  props: {
    goToSomePage: {
      type: Function,
      default: function(){ this.$router.push({ name: 'some-page' }) }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

匿名函数使用封闭范围,因此您不必自行绑定它。这意味着这里的匿名函数将使用与其他选项相同的作用域


Yon*_*uan 3

您的尝试不起作用的原因是:

  1. 您使用了箭头函数,其中thisis lexical
  2. Vue 不会自动将传递给props属性的函数与任何 Vue 实例绑定。所以this会自动绑定到window(全局)对象。

你可以尝试这样的事情:

new Vue({
  el: '#app',
  props: {
    goToSomePage: {
      type: Function
    }
  },
  computed: {
    computedGoToSomePage(){
      // If `goToSomePage` prop is provided, return that function
      if (typeof this.goToSomePage === 'function')
        return this.goToSomePage.bind(this);

      // Else, return your intended $router function here
      return (() => {
        /* UNCOMMENT THIS IN YOUR CODE */
        // this.$router.push({ name: 'some-page' })

        // This is to prove that `this` is referencing the Vue instance
        console.log(this);
      })
    }
  }
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>

<div id="app">
  <button @click="computedGoToSomePage">Go To Some Page</button>
</div>
Run Code Online (Sandbox Code Playgroud)

上面的方法利用computed属性来传递你的函数。使用它,Vue 神奇地绑定this到它的父 Vue 实例。