在渲染组件之前从API获取数据

2022-02-24 00:00:00 vue.js vue-router vue-component

在呈现页面之前,我正在发送2个API请求:

const Profile = {
    template: '#profile',
    attributes: null,
    photos: [],
    data: function () {
        return {attributes: Profile.attributes, photos: Profile.photos};
    },
    beforeRouteEnter: function (to, from, next) {
        function getProfile() {
            return axios.get('user/get-profile?access-token=1', {responseType: 'json'});
        }
        function getPhotos() {
            return axios.get('photos?access-token=1', {responseType: 'json'});
        }

        axios.all([getProfile(), getPhotos()])
            .then(axios.spread(function (profile, photos ) {
                console.log(profile, photos );
                next(vm => {
                    vm.setProfile(profile);
                    vm.setPhotos(photos);
                })
            }));
    },
    methods: {
        setProfile: function (response) {
            Profile.attributes = response.data;
            console.log(Profile.attributes);
        },
        setPhotos: function (response) {
            Profile.photos = response.data;
            console.log(response);
        },           
    }
};

问题是渲染发生在setProfilesetPhotos方法之前。如何正确呈现我的组件?


解决方案

评论中提到,第一个异步/等待解决方案有点误导,因为所有生命周期方法都是同步的。这是可行的,因为代码被转换为内部有生命周期的同步函数。

下面我添加了几个更新的代码段。

旧答案

使用异步/等待尝试。我已删除beforeRouteEnteraxios.spread并添加了create

const Profile = {
  template: '#profile',
  attributes: null,
  photos: [],
  data() {
    return {
      attributes: null,
      photos: null,
    };
  },
  async created() {
    const getProfile = await axios.get('user/get-profile?access-token=1');
    const getPhotos = await axios.get('photos?access-token=1');

    this.setProfile(profile);
    this.setPhotos(photos);
  },
  methods: {
    setProfile(response) {
      this.attributes = response.data;
      console.log(this.attributes);
    },
    setPhotos(response) {
      this.photos = response.data;
      console.log(response);
    },
  },
};

const Profile = {
  template: '#profile',
  attributes: null,
  photos: [],
  data() {
    return {
      attributes: null,
      photos: null,
    };
  },
  async created() {
    this.attributes = await axios.get('user/get-profile?access-token=1');
    this.photo = await axios.get('photos?access-token=1');
  },
};

已更新答案

您可以在生命周期方法中使用异步函数。

const Profile = {
  template: '#profile',
  attributes: null,
  photos: [],
  data() {
    return {
      attributes: null,
      photos: null,
    };
  },
  created() {
    const fetchData = async () => {
      const { data: attributes } = await axios.get(
        'user/get-profile?access-token=1'
      );
      const { data: photos } = await axios.get('photos?access-token=1');

      this.attributes = attributes;
      this.photos = photos;
    };

    fetchData();
  },
};

版本3和setup()

在Vue 3中,您可以使用async setup()。如果您使用它,您必须用Suspense包装您的组件。小心!本接口目前处于实验阶段https://v3.vuejs.org/guide/migration/suspense.html

<Suspense>
  <template #default>
    <YourComponent />
  </template>
  <template #fallback>
    <div>Loading ...</div>
  </template>
</Suspense>
export default {
  name: 'YourComponent',
  async setup() {
    const { data: attributes } = await axios.get('user/get-profile?access-token=1');
    const { data: photos } = await axios.get('photos?access-token=1');

    return {
      attributes,
      photos
    }
  }
}

相关文章