我已经关注了这篇文章,但问题是它只适用于一页。如何为不同的页面/组件制作它?
entry-client.js
require('./bootstrap');
import app from './app';
app.$mount('#app');
app.js
import App from './components/App.vue';
import Vue from 'vue';
export default new Vue({
render: h => h(App)
});
App.vue
<template>
<div id="app">
{{ message }}
</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello World'
}
},
}
</script>
entry-server.js
import app from './app';
renderVueComponentToString(app, (err, res) => {
print(res);
});
app.blade.php
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Example</title>
</head>
<body>
{!! $ssr !!}
<script src="{{ asset('js/entry-client.js') }}" type="text/javascript"></script>
</body>
</html>
AppController.php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\File;
class AppController extends Controller
{
private function render() {
$renderer_source = File::get(base_path('node_modules/vue-server-renderer/basic.js'));
$app_source = File::get(public_path('js/entry-server.js'));
$v8 = new \V8Js();
ob_start();
$js =
<<<EOT
var process = { env: { VUE_ENV: "server", NODE_ENV: "production" } };
this.global = { process: process };
EOT;
$v8->executeString($js);
$v8->executeString($renderer_source);
$v8->executeString($app_source);
return ob_get_clean();
}
public function get() {
$ssr = $this->render();
return view('app', ['ssr' => $ssr]);
}
}
在app.js
文件中,我需要其他页面/组件。当然,它们应该像以前一样自动包含在内。在此之前,我已经导入了所有组件。PHP 文件(Laravel 刀片)中使用的那些将被执行。
我以前拥有的(例如):
app.js
import Vue from 'vue';
const app = new Vue({
components: {
Products: () => import('./components/Products'),
Posts: () => import('./components/Posts'),
ExampleWidget: () => import('./components/ExampleWidget'),
},
el: '#app',
data() {
return {}
}
});
products.blade.php
@extends('layout.default')
@section('content')
<products :items="{{ json_encode($products) }}"></products>
<example-widgets :data="{{ json_encode($data) }}"></example-widgets>
@endsection
如何将其转换为服务器端渲染输出?我应该修改app.js
文件以导入所有组件吗?如果是,我是否应该动态地将组件传递给render: h => h(App)
. 我怎样才能实现它?