gpt4 book ai didi

javascript - 无法从组件方法访问数据

转载 作者:搜寻专家 更新时间:2023-10-30 22:27:12 24 4
gpt4 key购买 nike

我尝试了 vue js 中的组件方法。我的代码是这样的。

const Thread = Vue.component('threadpage', function(resolve) {
$.get('templates/thread.html').done(function(template) {
resolve({
template: template,
data: function() {
return {
data: {
title: "Data Table",
count: this.GetData
}
};
},
methods: {
GetData: function() {
var data = {
username : "newshubid",
data : {
page : 0,
length : 10,
schedule : "desc"
}
};
var args = {"data" : JSON.stringify(data)};
var params = $.param(args);

var url = "http://example-url";

var result;

DoXhr(url, params, function(response){
result = JSON.parse(response).data;
console.log("load 1", result);
});

setTimeout(function () {
console.log("load 2", result);
return result;
}, 1000);
}
},
created: function(){
this.GetData();
}
});
});
});

但是,当我尝试在模板中使用 {{ data.count }} 时。没有显示我想要的结果。即使我尝试在 GetData 中返回结果。

我的问题是什么?以及如何从方法中访问数据?请帮助我,我是初学者。谢谢

最佳答案

查看我在下面添加的编辑代码和注释。
您尝试在 setTimeout 的函数中使用 return 返回结果,这不会帮助您从 GetData 返回值。
相反,您可以只在 ajax 请求的回调函数中设置值。

const Thread = Vue.component('threadpage', function(resolve) {
$.get('templates/thread.html').done(function(template) {
resolve({
template: template,
data: function() {
return {
data: {
title: "Data Table",
// NOTE just set an init value to count, it will be refreshed when the function in "created" invoked.
count: /* this.GetData */ {}
}
};
},
methods: {
GetData: function() {
var data = {
username : "newshubid",
data : {
page : 0,
length : 10,
schedule : "desc"
}
};
var args = {"data" : JSON.stringify(data)};
var params = $.param(args);

var url = "http://example-url";

var result;
var vm = this;
DoXhr(url, params, function(response){
result = JSON.parse(response).data;
// NOTE set data.count to responsed result in callback function directly.
vm.data.count = result;
});
// NOTE I think you don't need code below anymore.
// setTimeout(function () {
// console.log("load 2", result);
// return result;
// }, 1000);
}
},
created: function(){
this.GetData();
}
});
});
});

关于javascript - 无法从组件方法访问数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45340951/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com