我在 vue-cli 创建的 webpack 项目中使用 .vue 模板。
我通常使用“导出默认值”来导出文件,如下所示:
export default {
data () {
return {
message:''
};
},
...
在脚本的后面,当我尝试访问实例时,它似乎在任何函数或第三方库(如 axios)中,我必须在顶部编写类似的内容:
var app = this;
这样我就可以访问数据属性...例如:
var app = this;
axios.post('https://test.com/api/getMessage',{}).then(res => {
app.message = res.data.message
})
.catch(error => {
console.log(error)
});
但是调用 var app = this;所有的时间都变得很累。
我更愿意将实例放入变量中,例如:
let app = {
data () {
return {
message:''
};
},
methods :{
getMessage:function(){
axios.post('https://test.com/api/getMessage',{}).then(res => {
app.message = res.data.message
})
.catch(error => {
console.log(error)
});
}
}
}
但我不明白如何正确导出或导入它。似乎每个示例都只使用导出默认值。因此,重申我的问题,是否有更好/更智能的方法来导出和导入脚本,这样我就不必编写:
var app = this;
最佳答案
axios.post('https://test.com/api/getMessage',{}).then(res => {
this.message = res.data.message
})
这应该可行 - 箭头函数发生在它们编写的范围内,这意味着 this
将引用那里的 Vue 实例。如果您没有使用箭头函数,则必须专门绑定(bind)范围:
axios.post('https://test.com/api/getMessage',{}).then(function(res){
this.message = res.data.message
}.bind(this))
关于javascript - 如何在Vue.js中导出命名实例,停止使用: var app = this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47295332/