javascript - Vue.js 服务端渲染中的组件

标签 javascript vue-router server-side-rendering vue.js

我正在尝试让我的 Vue 应用程序具有服务器端渲染功能。我正在使用 vue-server-renderer ( https://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()

Returns an Array of the components (definition/constructor, not instances) matched by the current route. This is mostly used during server-side rendering to perform data prefetching.

如何解决这个问题?

最佳答案

我之前遇到过类似的问题,并通过执行以下操作成功预取数据:

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)
   }
},

关于javascript - Vue.js 服务端渲染中的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40673680/

相关文章:

javascript - 推送数组中属性的值

c# - 剑道用户界面 : How to get new file name in javascript after renaming uploaded file in controller

javascript - Angular 2 子路由

javascript - Vue-router 重载组件

vue.js - 如何在 google chrome 扩展的构建项目中使用 VUEJS3 显示路由器 View

node.js - "Invariant Violation"在服务器端使用 React Server renderToString

firebase - 如何在next.js中重定向到受限页面的登录页面?

javascript - Openlayers 3 获取谷歌地图基础层?

javascript - vue 路由器参数关于数据更改

javascript - 如何在带有 Nuxt.js 的项目中使用 stencil.js 进行 SSR(以及 SSR)