Quasar CLI with Vite - @quasar/app-vite
ssrContext
物件是 SSR 上下文,所有應用程式的 Vue 元件都以此上下文進行渲染。
用法
警告
ssrContext
物件僅在 SSR 建置中可用,在伺服器端編譯時 (當 process∙env∙SERVER === true
時)。
在其他地方,它被作為參數提供給啟動檔案、Vuex store 和 Vue Router 初始化函式,以及 preFetch 方法
// a boot file
export default ({ ..., ssrContext }) => { /* ... */ }
// src/router/index.[js|ts]
export default ({ ..., ssrContext }) { /* ... */ }
// src/store/index.[js|ts]
export default ({ ..., ssrContext }) { /* ... */ }
// with preFetch:
preFetch ({ ..., ssrContext }) { /* ... */ }
content_paste
您也可以在 Vue 元件中存取 ssrContext。以下是兩個範例,一個使用 Composition API,另一個使用 Options API
import { useSSRContext } from 'vue'
export default {
// ...
setup () {
// we need to guard it and call it only on SSR server-side:
const ssrContext = process.env.SERVER ? useSSRContext() : null
// ...do something with it
}
}
content_paste
ssrContext 的剖析
ssrContext: {
req, // Express.js object
res, // Express.js object
$q, // The Quasar's $q Object
state, // The Vuex state (ONLY if using the Vuex store)
nonce, // (optional to set it yourself)
// The global "nonce" attribute to use
onRendered, // Registers a function to be executed server-side after
// app has been rendered with Vue. You might need this
// to access ssrContext again after it has been fully processed.
// Example: ssrContext.onRendered(() => { /* ... */ })
rendered // (optional to set it yourself)
// Set this to a function which will be executed server-side
// after the app has been rendered with Vue.
// We recommend using the "onRendered" instead.
//
// Purpose: backward compatibility with Vue ecosystem packages
// (like @vue/apollo-ssr)
// Example: ssrContext.rendered = () => { /* ... */ }
}
content_paste
關於 “nonce” 屬性的用途的更多資訊,請參閱 MDN。
req
和 res
是 Express.js 用於當前伺服器客戶端的物件。req
的一個用例是存取 req.url
以獲取客戶端請求的 URL。
提示
也歡迎將您自己的東西注入 ssrContext,但請勿篡改任何私有屬性 (以底線開頭的屬性,例如 _someProp
)。