vuejs / vue2-ssr-docs

Vue.js Server-Side Rendering Guide (for Vue 2)
564 stars 239 forks source link

Describe how to add `asyncData` type in TypeScript #174

Open ktsn opened 6 years ago

ktsn commented 6 years ago

ref vuejs/vuex#1214

It maybe good if we have a docs for how to declare asyncData in TypeScript. It is not an API of any libraries, so we cannot directly declare it in any d.ts files. I guess it would be appropriate to describe it in the SSR docs.

yyx990803 commented 6 years ago

Yeah, feel free to submit a PR

TonyPythoneer commented 6 years ago

Maybe like this?

import Vue, { ComponentOptions } from "vue";
import { Store } from "vuex";
import { Route } from 'vue-router';

declare module "vue/types/options" {

    interface ComponentOptions<V extends Vue> {
        asyncData?: (store: Store<any>, route: Route) => Promise<any>;
    }
}

declare module "vue/types/vue" {
    interface Vue {
        asyncData?: (store: Store<any>, route: Route) => Promise<any>;
    }
}

But I am confused about this, it doesn't have a standard method or formal document mentions it.

joffreyBerrier commented 5 years ago

Do like this:

  @Component({
    async asyncData({ params, error }) {
     💀// impossible to use this.$http on @component 💀
      const http = Vue.prototype.$nuxt.$http;
      const payload1 = await http.get('/url')
      const payload2 = await http.post('/url', { params })

      return {
        data1: payload1.data,
        data2: payload2.data,
      }
    }
  })
  export default class NameOfYourClass extends Vue {
    name: 'NameOfYourClass'

    // AsyncData
    data1?: type
    data2?: type

    [...]
  }