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

时间:2018-04-29 16:25:12

标签: api vuejs2 vue-component

我正在开发一个简单的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: ['[{', '}]']
})

现在,我已经为故事,诗歌和许多其他事情复制了上述对象。但我最好将它们合二为一。我试图搜索的策略包括将父组件作为此对象,但我想我可能在考虑其中一些问题。 真的很感激帮助!

2 个答案:

答案 0 :(得分:1)

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

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>

答案 1 :(得分:0)

有很多方法可以解决这个问题,但也许一旦你在组件/应用程序状态模型中达到这种复杂程度,最明智的策略就是使用中央状态存储。

请参阅vue指南的State Management章节,可能还有优秀的vuex

您可以在适当的本地类/函数中考虑公共逻辑,并从存储操作中调用它们(对于必须使用actions的异步操作,这将在完成时提交mutations各自的状态更改异步操作。

相关问题