【发布时间】:2020-01-02 19:11:13
【问题描述】:
我有一个 vue2 组件,其中一些方法很长,有很多回调,我想更好地结构化它。我尝试按照callbackhell.com 遵循指导方针,但在 vue 方法中事情看起来并不那么容易。
以下是我目前所处位置的示例,它有效,但我对以下内容感到困惑:
Function hoisting 似乎在这里不起作用,我需要先定义我的函数,然后再运行它们,否则会触发错误。为什么会这样,我是不是漏掉了什么?
当我像这样定义内部函数时,我丢失了其中绑定到 Vue 组件的“this”。我在函数定义之后通过
.bind(this)修复它,它可以工作但看起来相当晦涩。有没有更好的方法在方法中定义实用函数,同时仍然保留“this”的上下文?这通常是在 Vue 中将函数添加到方法中的一种好方法吗?我知道我可以直接在
methods: {}对象中使它们成为同级方法,这解决了我的大部分问题,但由于它们仅与saveFavourites()方法相关而不与组件中的任何其他内容相关,因此将它们包装在我看来更干净?
非常感谢
methods: {
saveFavourites() {
var promptName = function() {
return this.$swal({
text: 'Enter name'),
content: 'input',
button: {
text: 'Save'),
closeModal: true,
},
})
}.bind(this);
var storePlan = function(name) {
if(!name || (name = name.trim()) === '' ) return;
axios.post('/api/user-store-daily-favourites', { meals: this.mealIds, name: name })
.then(response => {
if(response.data.status === 'success') {
this.$emit('dailyFavouritesUpdated');
}
});
}.bind(this);
// running it - if I move this above functions definitions, I get error
promptName()
.then( (name) => storePlan(name) );
},
【问题讨论】:
标签: vue.js vue-component hoisting