search

Home  >  Q&A  >  body text

javascript - How multiple components share the data returned by ajax

Get city components

city: {
        template: '#city_template',
        data: function () {
            return {
                cityData: cityData,//城市数据
                selectedOptions:[24,81],//被选中的城市
                list:[],
            }
        },
        mounted: function () {
                this.getCity()
        },
        methods: {
            getCity: function () {
                var self = this
                $.ajax({
                    url:'test.json',
                    success:function (res) {
                        self.$set(self.$data, 'cityData', res)
                    }
                })
            }
        }
    },

A page may have multiple such components. In this case, multiple ajax requests will be requested. In fact, the data is the same. Is there a way to only request asynchronous data once, and then use multiple such components? The same data? I tried defining ajax externally and assigning it to cityData, so the data cannot be updated directly

某草草某草草2747 days ago598

reply all(5)I'll reply

  • PHP中文网

    PHP中文网2017-05-19 10:18:17

    test.json is a file of yours. You can change it to the format of a .js file, and then directly change it to a variable. Obj={}; won’t it be obtained? Modular ones are also available.

    reply
    0
  • ringa_lee

    ringa_lee2017-05-19 10:18:17

    Look at your city component, city.data().cityData is the result set you want

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-19 10:18:17

    1. Manage with Vuex

    2. Maintain this value on the common parent component, pass it to the child component through props, and the child component notifies the parent component of ajax through $emit

    reply
    0
  • 某草草

    某草草2017-05-19 10:18:17

    Finally, we used asynchronous components

    Vue.component(ele,function (resolve, reject) {
                    getCity().then(function (data) {
                        resolve(comInherit.extend(obj[ele]));
                    }).catch(function (error) {
                        alert(error)
                    })
                });

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-19 10:18:17

    To share data between multiple components, you can use vuex or define a global one yourself

    reply
    0
  • Cancelreply