gpt4 book ai didi

api - 如何在vuejs中实现可重用的api调用组件?

转载 作者:行者123 更新时间:2023-12-03 03:41:46 24 4
gpt4 key购买 nike

我正在开发一个简单的 vuejs 应用程序,其中有一些相同的 API 提供以类似方式解析的内容。我希望编写代码来获取各种 API 调用中通用的内容,并且只需要将 API 端点传递给获取内容的内容即可。

这是我的代码

var content = new Vue({
el: '#story',
data: {
loaded: [],
current: 0,
hasMore:"",
nextItems:"",
errors: []
},
mounted() {
axios.get("/storyjs")
.then(response => {
this.loaded = this.loaded.concat(response.data.content)
this.hasMore = response.data.hasMore
this.nextItems = response.data.nextItem
}).catch(e => {
this.errors.push(e)
})
},
methods: {
fetchNext: function() {
axios.get(this.nextItems)
.then(response => {
this.loaded = this.loaded.concat(response.data.content)
this.hasMore = response.data.hasMore
this.nextItems = response.data.nextItem
this.current+=1
}).catch(e => {
//TODO CLEAR errors before pushing
this.errors.push(e)
})
},
next: function() {
if (this.current+1 < this.loaded.length) {
this.current+=1
} else {
this.fetchNext()
}
},
prev: function() {
this.current = (this.current-1 >= 0) ? this.current-1 : 0
}
},
delimiters: ['[{', '}]']
})

现在,我已经将上述对象复制到故事、诗歌和许多其他内容中。但我理想地希望将它们合二为一。我尝试搜索的策略包括将父组件作为该对象,但我认为我可能对其中一些想法是错误的。非常感谢您的帮助!

最佳答案

我选择了mixin。这是我实现的解决方案。

apiObject.js(可重用对象)

var apiObject = {
data: function() {
return {
loaded: [],
current: 0,
hasMore: "",
nextItems: "",
errors: []
};
},
methods: {
fetchContent: function(apiEndpoint) {
axios
.get(apiEndpoint)
.then(response => {
this.loaded = this.loaded.concat(response.data.content);
this.hasMore = response.data.hasMore;
this.nextItems = response.data.nextItem;
})
.catch(e => {
this.errors.push(e);
});
},
fetchNext: function() {
axios
.get(this.nextItems)
.then(response => {
this.loaded = this.loaded.concat(response.data.content);
this.hasMore = response.data.hasMore;
this.nextItems = response.data.nextItem;
this.current += 1;
})
.catch(e => {
//TODO CLEAR errors before pushing
this.errors.push(e);
});
},
next: function() {
if (this.current + 1 < this.loaded.length) {
this.current += 1;
} else if (this.hasMore == true) {
this.fetchNext();
}
},
prev: function() {
this.current = this.current - 1 >= 0 ? this.current - 1 : 0;
}
}
};

story.js(具体用法)

var storyComponent = Vue.extend({
mixins: [apiObject],
created() {
this.fetchContent("/story");
}
});

new Vue({
el: "#story",
components: {
"story-component": storyComponent
},
delimiters: ["[{", "}]"]
});

然后,您可以在组件本身中定义模板,或者使用 inline-template 方式在 html 文件中创建模板,这就是我所做的

output.html 包含所有 js 文件

<div id="story">
<story-component inline-template>
[{loaded[current].title}]
</story-component>
</div>

关于api - 如何在vuejs中实现可重用的api调用组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50088813/

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