export default {
props: {
goToSomePage: {
type: Function,
default: () => { this.$router.push({ name: 'some-page' }) }
}
}
}
我想做这样的事情,但“这个”是未定义的。
有什么方法可以解决这个问题吗?
我想给出一个默认动作,并在回调函数中使用“this”。
您的尝试不起作用的原因是:
this
is lexical的箭头功能。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实例。