search

Home  >  Q&A  >  body text

javascript - How to extract public methods in components with vue-cli

The question is the same as the title.
Additional description:
The project uses vuex, vue-router, vue-router will load data through ajax every time it switches to one side, and the method of loading data on each page is the same. I tried placing the public method in main.js and then calling it in the component. I found that the method can be called, but due to the asynchronous nature of ajax, the value cannot be transferred back to the submodule. Has anyone encountered such a situation? How to solve it? Thanks!

怪我咯怪我咯2792 days ago930

reply all(2)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-19 10:36:30

    Return a promise is enough
    For example:

    main.js
    function ajaxMethod() {
        return ajax({
            url: 'xxx',
            data: xxx
        })
    }
    component:
    ajaxMethod().then((result) => {
        console.log(result)
    })

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-19 10:36:30


    You can use vue-resource, like me. Put the api in a separate file and load it into Vue, then you can solve the problem of writing the same api multiple times

    reply
    0
  • Cancelreply