簡體   English   中英

Vue.js服務器端呈現中的組件

[英]Component in Vue.js server-side rendering

我試圖讓我的Vue應用程序具有服務器端渲染。 我正在使用vue-server-rendererhttps://www.npmjs.com/package/vue-server-renderer )。 客戶端渲染工作正常。

我的應用程序使用vue-routeraxios

這是我的server.js

server.get('*', (request, response) => {
  bundleRenderer.renderToString({ url: request.url }, (error, htmlPromise) => {
    if (error) {
      // Log the error in the console
      console.error(error)
      // Tell the client something went wrong
      return response
        .status(500)
        .send(error)
    }
    response.send(layout.replace('<div id=app></div>', htmlPromise))
  })
})

getInfo()是獲取服務器數據的方法。

這是getInfo()

export default {
  methods: {
    getInfo(api) {
        return axios
          .get(api || this.$route.params.path)
          .then((data) => {
            this.data = data
            this.$set(this, 'isLoading', false)
          })
    },
  },
}

我的服務器條目是:

import { app, router, store } from './index'

export default context => {

  let componentPromises = router.getMatchedComponents().filter((component) => {
    return component.methods && component.methods.getInfo
  }).map((component) => {
    return component.methods.getInfo()
  })

  return Promise.all(componentPromises).then(() => {
    return app
  })
}

但是,我很快意識到router.getMatchedComponents()所有組件都沒有$route$set 因此,方法getInfo()停止工作。

來自https://router.vuejs.org/en/api/router-instance.html的文檔非常簡短,並未提供太多信息:

router.getMatchedComponents()

返回由當前路由匹配的組件(定義/構造函數,而不是實例)的數組。 這主要在服務器端渲染期間用於執行數據預取。

我該如何解決這個問題?

我之前遇到過類似的問題,並通過執行以下操作成功預取數據:

app.$router.onReady(() => {
   const matchedComponents = app.$router.getMatchedComponents()

   if (!matchedComponents.length) { /* ... */}

   Promise.all(matchedComponents.map((Component: any) => {
     if (Component.options.methods.asyncData) {
       return Component.options.methods.asyncData({
         store: app.$store,
         route: app.$router.currentRoute
       });
     }
   })).then(() => { /* your callback here ... */ });
}

根據vue ssr文檔( https://ssr.vuejs.org/en/data.html ),建議的方法是在組件中使用自定義asyncData方法來執行數據提取,而不是直接調用組件方法:

export default {
   asyncData ({ store, route }) {
      // return the Promise from the action
      return store.dispatch('fetchItem', route.params.id)
   }
},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM