我正在创建一个Vue.js组件,该组件使用render()方法返回html代码。 render()方法的结构就是代码中所示的结构。
render: function (h, context) {
// Element returned by the render function
var element;
// .... code that performs initializations
// The invocation of a promise that downloads a json file
var promise = loadJsonFile (pathFile);
promise.then (
// on success
function (jsonFile) {
// ... here is some code that builds an element as
// a function of json file contents
element = buildComponent (jsonFile, h, context);
},
// on error
function (error) {
console.log(error);
}
);
// Then the variable element returns "nothing"
return (element);
}
如何返回构造的“ element”对象,或者可以在返回之前“等待”执行“ function(jsonFile)”块?
答案 0 :(得分:0)
尝试从buildComponent
返回元素,并使用另一种then
方法等待结果:
render: function (h, context) {
// Element returned by the render function
var element;
// .... code that performs initializations
// The invocation of a promise that downloads a json file
var promise = loadJsonFile (pathFile);
promise.then (
// on success
function (jsonFile) {
// ... here is some code that builds an element as
// a function of json file contents
// return the result of 'buildComponent', throwing another promise
// which can be caught with another then statement below
return buildComponent (jsonFile, h, context);
},
// on error
function (error) {
console.log(error);
}
)
.then(function(element) {
// do things with 'element'
})
// catch any massive explosions (errors)
.catch(function(error) { console.log(error); });
}