我正在尝试让我的 Vue 应用程序具有服务器端渲染功能。我正在使用 vue-server-renderer ( https://www.npmjs.com/package/vue-server-renderer )。客户端渲染工作正常。
我的应用程序使用vue-router
和axios
这是我的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/