关于前端:Vue-ssr

8次阅读

共计 1844 个字符,预计需要花费 5 分钟才能阅读完成。

  1. 组件生命周期钩子函数

应该防止在 beforeCreatecreated 生命周期时产生全局副作用的代码。
例如:
其中应用 setInterval 设置 timer。在纯客户端 (client-side only) 的代码中,咱们能够设置一个 timer,而后在 beforeDestroydestroyed 生命周期时将其销毁。
然而,因为在 SSR 期间并不会调用销毁钩子函数,所以 timer 将永远保留下来。为了防止这种状况,请将副作用代码移动到 beforeMountmounted 生命周期中。

2 路由懒加载。

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

export function createRouter () {
  return new Router({
    mode: 'history',
    routes: [{ path: '/', component: () => import('./components/Home.vue') },
      {path: '/item/:id', component: () => import('./components/Item.vue') }
    ]
  })
}

3 应用 Ui 框架上按需引入,按需加载。

routes: [{ path: "/", redirect: "index"},
    {
    path: "/",
    name: "home",
    component: resolve=>require(["@/views/home"],resolve),
    children: [
      {
        // 员工查问
        path: "/employees",
        component: resolve=>require(["@/components/employees"],resolve)
      },
    {
      // 首页
      path: "/index",
      component: resolve=>require(["@/views/index"],resolve)
    },

4 gzip 压缩

cnpm i compression-webpack-plugin -D

在 vue.congig.js 中引入并批改 webpack 配置:~~~~

    const CompressionPlugin = require('compression-webpack-plugin')

configureWebpack: (config) => {if (process.env.NODE_ENV === 'production') {
            // 为生产环境批改配置...
            config.mode = 'production'
            return {
                plugins: [new CompressionPlugin({
                    test: /\.js$|\.html$|\.css/, // 匹配文件名
                    threshold: 10240, // 对超过 10k 的数据进行压缩
                    deleteOriginalAssets: false // 是否删除原文件
                })]
            }
        }

在 index.js 中退出如下代码

productionGzip: false,
    
productionGzipExtensions: ['js', 'css']

5 应用 cdn

<body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
script src="https://unpkg.com/jquery@3.3.1/dist/jquery.js"></script> 
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<div id="app">    
 </div>
</body>

而后在 webpack.base.conf.js 中退出 externals

module.exports = {context: path.resolve(__dirname, '../'),
    
entry: {app: './src/main.js'},
externals: {
'jquery': 'jQuery',
    
'element-ui':'ELEMENT',
    
 'vue': 'Vue'
  1. 代码方面
  • v-if 和 v-show 依据场景抉择应用。
  • 为 item 设置惟一 key 值,在列表数据遍历渲染时,为每一项 item 设置惟一的 key, 不便 vue 外部准确的找到该 item, 当 state 更新时,新的状态值和旧的状态值进行比照,较快的定位到。
  1. 用户体验上动手。

    • 应用 better-click.js,解决 Iphone, 点击有 300 毫秒的问题。
    • 菊花 Loading。
    • 骨架屏。
正文完
 0