1. <meter id="vu1l5"></meter>

        \n  <\/div>\n  

        亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

        Home Web Front-end Front-end Q&A Does vue3.0 support server-side rendering?

        Does vue3.0 support server-side rendering?

        Dec 15, 2022 pm 02:47 PM
        vue vue3 Server-side rendering

        vue3.0 supports server-side rendering. Vue supports rendering components directly into HTML strings on the server side, returning them to the browser as a server-side response, and finally "activating" (hydrate) the static HTML on the browser side into an interactive client application. A server-rendered Vue application can be considered "isomorphic" or "universal" because most of the application's code runs on both the server and the client. Advantages of Vue using server-side rendering: Faster first screen Loading, unified mental model, better SEO.

        Does vue3.0 support server-side rendering?

        The operating environment of this tutorial: windows7 system, vue3 version, DELL G3 computer.

        vue supports server-side rendering (SSR).

        Vue.js is a framework for building client-side applications. By default, the responsibility of the Vue component is to generate it in the browser and operate DOM. However, Vue also supports rendering components directly into HTML strings on the server side, returning them to the browser as a server-side response, and finally "activating" (hydrate) the static HTML on the browser side for clients who can interact. Side application.

        A Vue.js application rendered by the server can also be considered "isomorphic" (Isomorphic) or "universal" (Universal), because most of the application's code runs simultaneously on Server and client.

        Why use server-side rendering (SSR)?

        Compared with client-side single-page application (SPA) Compared with SSR, the main advantages of SSR are:

        • Faster first screen loading: This is especially important on slow network speeds or slow-running devices. Server side The rendered HTML doesn't have to wait for all JavaScript to be downloaded and executed before it's displayed, so your users will see the fully rendered page faster. In addition, the data retrieval process is completed server-side on the first visit, There may be a faster database connection than fetching from the client. This usually leads to higher core web metric scores, better user experience, and for those "first screen loading speed is directly related to conversion rate" For applications, this may be crucial. [Related recommendations: vuejs video tutorial, web front-end development]

        • Unified mental model: You can develop the entire application using the same language and the same declarative, component-oriented mental model without having to switch back and forth between the back-end template system and the front-end framework.

        • Better SEO: Search engine crawlers can see the fully rendered page directly.

        There are some trade-offs when using SSR Things to consider:

        • Limitations in development. Specific code on the browser side can only be used in certain life cycle hooks; some external libraries may require special processing to be used on the server side. Run within a rendered application.

        • More requirements related to build configuration and deployment. Server-side rendering applications require an environment that allows the Node.js server to run. Unlike completely static SPA, which can be deployed on any static file server.

        • Higher server load. Rendering a complete app in Node.js is more CPU intensive than just hosting static files, so if you anticipate high traffic, prepare for the corresponding server load and adopt a sensible caching strategy.

        Server Side Rendering (SSR) vs. Static Site Generation (SSG)

        Static Site Generation (Static-Site Generation, abbreviated as SSG), also known as Pre-rendering, is another popular technology for building fast websites. If the data required to render a page server-side is the same for every user, then we can render it only once and do it ahead of time during the build process, rather than re-rendering the page every time a request comes in. Pre-rendered pages are generated and hosted on the server as static HTML files.

        SSG retains the same performance as SSR applications: it brings excellent first-screen loading performance. At the same time, it is less expensive and easier to deploy than SSR applications because it outputs static HTML and resource files. The key word here is static: SSG can only be used for pages that consume static data, i.e. the data is known during build time and does not change across multiple deployments. Whenever the data changes, it needs to be redeployed.

        If you are investigating SSR only to optimize the SEO of a few marketing pages (such as /, /about and /contact, etc.), then you may need SSG instead of SSR. SSG is also great for building content-based websites, such as documentation sites or blogs. In fact, the website you are reading now was statically generated using VitePress, a static site generator powered by Vue.

        Hello World

        Get ready to experience server-side rendering in action. Server-side rendering (ie SSR) sounds complicated, but a simple Node script only requires 3 steps to achieve this function:

        // 步驟 1:創(chuàng)建一個Vue實(shí)例
        var Vue = require(&#39;vue&#39;)
        var app = new Vue({
          render: function (h) {
            return h(&#39;p&#39;, &#39;hello world&#39;)
          }
        })
        
        // 步驟 2: 創(chuàng)建一個渲染器
        var renderer = require(&#39;vue-server-renderer&#39;).createRenderer()
        
        // 步驟 3: 將 Vue實(shí)例 渲染成 HTML
        
        renderer.renderToString(app, function (error, html) {
          if (error) throw error
          console.log(html)
          // => <p server-rendered="true">hello world</p>
        })

        It's not difficult. Of course, this example is simpler than most applications to explore how these functions work

        Simple server-side rendering through Express Web server

        It's hard to say server-side rendering without a web server, so let's supplement it. We will build a very simple server-side rendering application using only ES5 and no other build steps or Vue plugins.

        Launch an app that tells users how much time they spent on a page.

        new Vue({
          template: &#39;<div>你已經(jīng)在這花了 {{ counter }} 秒。</div>&#39;,
          data: {
            counter: 0
          },
          created: function () {
            var vm = this
            setInterval(function () {
              vm.counter += 1
            }, 1000)
          }
        })

        In order to adapt to server-side rendering, we need to make some modifications so that it can be rendered in the browser and Node:

        • In the browser, change our The application instance is added to the global context (window) and we can install it.

        • In Node, exporting a factory function allows us to create an application instance for each request.

        A little template is needed to implement this:

        // assets/app.js
        (function () { &#39;use strict&#39;
          var createApp = function () {
            // ---------------------
            // 開始常用的應(yīng)用代碼
            // ---------------------
        
            // 主要的Vue實(shí)例必須返回,并且有一個根節(jié)點(diǎn)在id "app"上,這樣客戶端可以加載它。
        
            return new Vue({
              template: &#39;<div id="app">你已經(jīng)在這花了 {{ counter }} 秒。</div>&#39;,
              data: {
                counter: 0
              },
              created: function () {
                var vm = this
                setInterval(function () {
                  vm.counter += 1
                }, 1000)
              }
            })
        
            // -------------------
            // 結(jié)束常用的應(yīng)用代碼
            // -------------------
          }
          if (typeof module !== &#39;undefined&#39; && module.exports) {
            module.exports = createApp
          } else {
            this.app = createApp()
          }
        }).call(this)

        Now that we have the application code, add an html file.

        <!-- index.html -->
        <!DOCTYPE html>
        <html>
        <head>
          <title>My Vue App</title>
          <script src="/assets/vue.js"></script>
        </head>
        <body>
          <div id="app"></div>
          <script src="/assets/app.js"></script>
          <script>app.$mount(&#39;#app&#39;)</script>
        </body>
        </html>

        Mainly refer to the app.js we created previously in the assets folder, and the vue.js file, we have a single-page application that can run

        Then in order to implement server-side rendering , a step needs to be added on the server side.

        // server.js
        &#39;use strict&#39;
        
        var fs = require(&#39;fs&#39;)
        var path = require(&#39;path&#39;)
        
        // 定義全局的Vue為了服務(wù)端的app.js
        global.Vue = require(&#39;vue&#39;)
        
        // 獲取HTML布局
        var layout = fs.readFileSync(&#39;./index.html&#39;, &#39;utf8&#39;)
        
        // 創(chuàng)建一個渲染器
        var renderer = require(&#39;vue-server-renderer&#39;).createRenderer()
        
        // 創(chuàng)建一個Express服務(wù)器
        var express = require(&#39;express&#39;)
        var server = express()
        
        // 部署靜態(tài)文件夾為 "assets"文件夾
        server.use(&#39;/assets&#39;, express.static(
          path.resolve(__dirname, &#39;assets&#39;)
        ))
        
        // 處理所有的Get請求
        server.get(&#39;*&#39;, function (request, response) {
          // 渲染我們的Vue應(yīng)用為一個字符串
          renderer.renderToString(
            // 創(chuàng)建一個應(yīng)用實(shí)例
            require(&#39;./assets/app&#39;)(),
            // 處理渲染結(jié)果
            function (error, html) {
              // 如果渲染時發(fā)生了錯誤
              if (error) {
                // 打印錯誤到控制臺
                console.error(error)
                // 告訴客戶端錯誤
                return response
                  .status(500)
                  .send(&#39;Server Error&#39;)
              }
              // 發(fā)送布局和HTML文件
              response.send(layout.replace(&#39;<div id="app"></div>&#39;, html))
            }
          )
        })
        
        // 監(jiān)聽5000端口
        server.listen(5000, function (error) {
          if (error) throw error
          console.log(&#39;Server is running at localhost:5000&#39;)
        })

        That’s it. Entire example, clone it for in-depth experiment. Once it's running locally, you can confirm that the service selected by Renderer is actually running by right-clicking on the page and selecting Page Resources (or similar). You can see in the body:

        <div id="app" server-rendered="true">You have been here for 0 seconds&period;</div>

        instead of:

        <div id="app"></div>

        Streaming response

        Vue also supports streaming rendering , the preference applies to web servers that support streaming. Allows HTML to be generated and written generally to the corresponding stream, rather than being written all at once. The result is that requests are served faster, with no drawbacks!

        In order to make the application code in the previous section suitable for streaming rendering, you can simply replace server.get('*',...) with the following code:

        // 拆分布局成兩段HTML
        var layoutSections = layout.split('<div id="app"></div>')
        var preAppHTML = layoutSections[0]
        var postAppHTML = layoutSections[1]
        
        // 處理所有的Get請求
        server.get('*', function (request, response) {
          // 渲染我們的Vue實(shí)例作為流
          var stream = renderer.renderToStream(require('./assets/app')())
        
          // 將預(yù)先的HTML寫入響應(yīng)
          response.write(preAppHTML)
        
          // 每當(dāng)新的塊被渲染
          stream.on('data', function (chunk) {
            // 將塊寫入響應(yīng)
            response.write(chunk)
          })
        
          // 當(dāng)所有的塊被渲染完成
          stream.on('end', function () {
            // 將post-app HTML寫入響應(yīng)
            response.end(postAppHTML)
          })
        
          // 當(dāng)渲染時發(fā)生錯誤
          stream.on('error', function (error) {
            // 打印錯誤到控制臺
            console.error(error)
            // 告訴客服端發(fā)生了錯誤
            return response
              .status(500)
              .send('Server Error')
          })
        })

        This is no better than the previous one Versioning is complex, and even this may not be a new concept to you. We did:

        • Build the stream

        • Write the HTML before applying the response

        • In Apply HTML to write response when available

        • Write HTML at the end of response

        • Handle any errors

        Component Caching

        Vue’s server-side rendering is very fast by default, but you can further improve performance by caching rendered components. This is considered an advanced feature, however, if the wrong component is cached (or the correct component has the wrong content) it will cause the app to render incorrectly. Special note:

        Components containing subcomponents that depend on global state (such as state from vuex) should not be cached. If you do this, the subcomponent (in fact the entire subtree) will also be cached. So pay special attention to situations with slots fragments or subcomponents.

        Settings

        Outside of warning conditions, we can use the following method to cache components.

        First, you need to provide a cache object to the renderer. Here's a simple example using lru-cache

        var createRenderer = require(&#39;vue-server-renderer&#39;).createRenderer
        var lru = require(&#39;lru-cache&#39;)
        
        var renderer = createRenderer({
          cache: lru(1000)
        })

        which will cache up to 1000 independent renders. For further configuration of caching into content, see lru-cache settings

        Then for the components you want to cache, you can provide them with:

        • A unique name

        • A serverCacheKey function, returns a unique component scope

        For example:

        Vue.component({
          name: &#39;list-item&#39;,
          template: &#39;<li>{{ item.name }}</li>&#39;,
          props: [&#39;item&#39;],
          serverCacheKey: function (props) {
            return props.item.type + &#39;::&#39; + props.item.id
          }
        })

        Ideal components for caching

        Any pure component can be safely cached - this is to ensure that passing the same data to any component will produce the same HTML. Examples of these scenarios include:

        • Static components (e.g. always try the same HTML, so the serverCacheKey function can return true)

        • List components (caching them can improve performance when you have large lists) )

        • Explanation:

        Now, you should understand the basic concepts behind server-side rendering. However, the build process, routing, and Vuex each have their own considerations. (Learning video sharing:

        vuejs introductory tutorial

        ,

        Basic programming video

        )

        The above is the detailed content of Does vue3.0 support server-side rendering?. For more information, please follow other related articles on the PHP Chinese website!

        Statement of this Website
        The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

        Hot AI Tools

        Undress AI Tool

        Undress AI Tool

        Undress images for free

        Undresser.AI Undress

        Undresser.AI Undress

        AI-powered app for creating realistic nude photos

        AI Clothes Remover

        AI Clothes Remover

        Online AI tool for removing clothes from photos.

        Clothoff.io

        Clothoff.io

        AI clothes remover

        Video Face Swap

        Video Face Swap

        Swap faces in any video effortlessly with our completely free AI face swap tool!

        Hot Tools

        Notepad++7.3.1

        Notepad++7.3.1

        Easy-to-use and free code editor

        SublimeText3 Chinese version

        SublimeText3 Chinese version

        Chinese version, very easy to use

        Zend Studio 13.0.1

        Zend Studio 13.0.1

        Powerful PHP integrated development environment

        Dreamweaver CS6

        Dreamweaver CS6

        Visual web development tools

        SublimeText3 Mac version

        SublimeText3 Mac version

        God-level code editing software (SublimeText3)

        How to develop a complete Python Web application? How to develop a complete Python Web application? May 23, 2025 pm 10:39 PM

        To develop a complete Python Web application, follow these steps: 1. Choose the appropriate framework, such as Django or Flask. 2. Integrate databases and use ORMs such as SQLAlchemy. 3. Design the front-end and use Vue or React. 4. Perform the test, use pytest or unittest. 5. Deploy applications, use Docker and platforms such as Heroku or AWS. Through these steps, powerful and efficient web applications can be built.

        How to start a vue project with vscode How to start a vue project with vscode Apr 16, 2025 am 06:15 AM

        Starting a Vue.js project in VSCode requires the following steps: Installing Vue.js CLI Create a new project Installation dependencies Starting the project in Terminal Open the project in VSCode Run the project again in VSCode

        Laravel Vue.js single page application (SPA) tutorial Laravel Vue.js single page application (SPA) tutorial May 15, 2025 pm 09:54 PM

        Single-page applications (SPAs) can be built using Laravel and Vue.js. 1) Define API routing and controller in Laravel to process data logic. 2) Create a componentized front-end in Vue.js to realize user interface and data interaction. 3) Configure CORS and use axios for data interaction. 4) Use VueRouter to implement routing management and improve user experience.

        How to debug vue project with vscode How to debug vue project with vscode Apr 16, 2025 am 07:00 AM

        Steps to debug a Vue project in VS Code: Run the project: npm run serve or yarn serve Open the debugger: F5 or "Start debug" button Select "Vue: Attach to Chrome" configuration attached to the browser: VS Code automatically attached to the project running in Chrome Settings Breakpoint Start debug: F5 or "Start debug" button Step by step: Use the debug toolbar button to execute the code step by step Check variables: "Surveillance" window

        How to configure vue with vscode How to configure vue with vscode Apr 16, 2025 am 07:06 AM

        How to configure VSCode to write Vue: Install the Vue CLI and VSCode Vue plug-in. Create a Vue project. Set syntax highlighting, linting, automatic formatting, and code snippets. Install ESLint and Prettier to enhance code quality. Integrated Git (optional). After the configuration is complete, VSCode is ready for Vue development.

        How to run vue with vscode How to run vue with vscode Apr 16, 2025 am 07:39 AM

        Running a Vue project in VSCode requires the following steps: 1. Install the Vue CLI; 2. Create a Vue project; 3. Switch to the project directory; 4. Install project dependencies; 5. Run the development server; 6. Open the browser to visit http://localhost:8080.

        How to separate the front and back end of wordpress How to separate the front and back end of wordpress Apr 20, 2025 am 08:39 AM

        It is not recommended to directly modify the native code when separating WordPress front and back ends, and it is more suitable for "improved separation". Use the REST API to obtain data and build a user interface using the front-end framework. Identify which functions are called through the API, which are retained on the backend, and which can be cancelled. The Headless WordPress mode allows for a more thorough separation, but it is more cost-effective and difficult to develop. Pay attention to security and performance, optimize API response speed and cache, and optimize WordPress itself. Gradually migrate functions and use version control tools to manage code.

        How to push the video stream of Hikvision camera SDK to the front-end Vue project for real-time playback? How to push the video stream of Hikvision camera SDK to the front-end Vue project for real-time playback? Apr 19, 2025 pm 07:42 PM

        How to push video streams from Hikvision camera SDK to front-end Vue project? During the development process, you often encounter videos that need to be captured by the camera to be circulated...

        See all articles