javascript - How multiple components share the data returned by ajax
某草草
某草草 2017-05-19 10:16:17
0
5
597

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

某草草
某草草

reply all(5)
洪涛

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.

左手右手慢动作

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

曾经蜡笔没有小新
  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

某草草

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)
                })
            });
淡淡烟草味

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template