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

问题描述 投票:0回答:1
export default {
  props: {
    goToSomePage: {
      type: Function,
      default: () => { this.$router.push({ name: 'some-page' }) }
    }
  }
}

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

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

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

javascript vue.js vuejs2 vue-component
1个回答
1
投票

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

  1. 你使用this is 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);
      })
    }
  }
});
<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>

上面的方法使用computed property来传递你的功能。使用它,Vue神奇地将this绑定到其父Vue实例。

© www.soinside.com 2019 - 2024. All rights reserved.