Vue.js 如何在vuejs单文件组件中的组件中引用自身
这是我的代码:Vue.js 如何在vuejs单文件组件中的组件中引用自身,vue.js,Vue.js,这是我的代码: export default { data(){ return { list: {} } }, components: { listFields : ListFields }, methods : { submitForm(data){ let
export default {
data(){
return {
list: {}
}
},
components: {
listFields : ListFields
},
methods : {
submitForm(data){
let vm = this;
console.log(vm);
axios.post('/api/dashboard/lists/create', data)
.then(function (response) {
this.$router.push({path: 'show-list', params: {list_id: response.data.id}});
}).catch(function (error) {
console.log(error);
})
}
}
}
问题是,在我调用“this.$router.push”的方法中,它抛出了一个错误,因为它引用了函数。但问题是我不能引用vm,因为我正在导出组件。我怎样才能解决这个问题 回调函数不知道外部上下文 使用.bind(this)或声明var=this
axios.post('/api/dashboard/lists/create', data)
.then(function (response) {
this.$router.push({path: 'show-list', params: {list_id: response.data.id}});
}.bind(this)).catch(function (error) {
console.log(error);
})
或
更新:
由于某种原因,似乎什么都不起作用,您可以尝试以下方法:为回调声明一个单独的方法
methods : {
submitForm(data){
axios.post('/api/dashboard/lists/create', data)
.then(this.onSuccess)
.catch(function (error) {
console.log(error);
})
},
onSuccess(response) {
this.$router.push({path: 'show-list', params: {list_id: response.data.id}});
}
}
使用
vm.$router
,顺便说一句,我不明白为什么您不能将它引用到vm
,它与导出的组件有什么关系?另一个选项是在axios方法中使用箭头语法。然后(response=>{this.$router.push(//etc)}
我实际上更喜欢使用.bind(this)使匿名函数知道上下文。您确定$router
已正确实例化吗?如果您在组件中添加了一个挂载的
处理程序和控制台.log(this.$router)
它是否返回值?如果没有,我们可以看看你是如何创建路由器的吗?@BertEvans,当我在created()中调用它时方法-它返回正确的值我在submitForm函数的顶部尝试过这个方法-但是它抛出了一个错误,$router没有push函数。你的console.log为vm返回了什么。$router?当我在submitForm函数中绑定它时,它返回“undefined”,当我从created()运行它时,{}组件实例的方法它返回正确的路由器实例您可以在调用submit方法的位置添加代码吗?
methods : {
submitForm(data){
axios.post('/api/dashboard/lists/create', data)
.then(this.onSuccess)
.catch(function (error) {
console.log(error);
})
},
onSuccess(response) {
this.$router.push({path: 'show-list', params: {list_id: response.data.id}});
}
}