美文网首页
nuxt2踩坑记录

nuxt2踩坑记录

作者: LemonTree7 | 来源:发表于2023-01-29 13:57 被阅读0次

    1.给nuxt配置sass

    node以及相关的sass-loader、node-sass版本对应

    node版本:v14.18.3
    node-sass版本:4.7.2
    sass-loader版本:7.3.1
    
    node版本:16.13.1
    node-sass版本:6.0.1
    sass-loader版本:10.0.1
    

    2.报错:The client-side rendered virtual DOM tree is not matching server-rendered content.

    报错原因:服务端与客户端渲染的DOM结构不一样。
    解决方法:在该element-ui组件最外层加上<client-only>组件,该组件只是占位且用于仅在客户端渲染其他组件。


    image.png

    3.nuxt使用axios的api接口

    1、增加plugins/api.js 文件,在plugins/api.js 中注入API方法, inject("api", API) 才能够应用$api;
    2、在 nuxt.config.js 中引入,plugins/api.js;
    3、在 asyncData 中应用

    async asyncData(context) {
        const routerInfo = context.params
        let moduleData = {}
        moduleData = await context.app.api.module1API.get()
        return { routerInfo, moduleData }
      },
    

    4.nuxt工程中如何去掉默认的白边

    1、先在nuxt.config.js中添加如下配置
    export default { head: { bodyAttrs: { class: 'body-class' }, } }
    2、在vue页面中添加如下样式即可:
    <style lang='stylus'> .body-class { height: 100%; margin:0; padding: 0; } </style>

    5.配置自定义路由

    将自定义路由替换掉nuxt自己生成的路由

    router: {
        extendRoutes(routes, resolve) {
          // 清空路由数组
          routes.splice(0)
          // 插入新的路由配置
          const routesArr = routerIndex.getRoutes(resolve);
          for (let index = 0; index < routesArr.length; index++) {
            routes.push(routesArr[index]);
          }
        }
      }
    

    6.报错:Do not mutate vuex store state outside mutation handlers.

    报错原因:在vuex中的action修改了state的数据,需要放到mutation当中进行修改;
    解决方案:修改state数据修改的位置,放到mutation。

    7. 打包生产环境下删除console.log,nuxt.js打包去除console

    1、下载babel-plugin-transform-remove-console插件

    npm install babel-plugin-transform-remove-console -D
    

    2、在nuxt.config.js最上边添加判断生产环境还是开发环境

    let plugins = []
    if (process.env.NODE_ENV === 'production') {
      plugins.push("transform-remove-console")
    }
    

    3、在nuxt.config.js的build里添加

    module.exports = {
      build: {
        babel: {
          plugins
        },
      }
    }
    

    8.部署

    1、对nuxt项目进行打包编译,输入指令npm run build,执行完会出现.nuxt文件夹,再执行npm run start
    2、将.nuxt,static,nuxt.config.js,package.json这四个文件夹复制上传到前端服务器,使用npm install,配置好之后使用npm run start。采用pm2守护进程,输入```pm2 start npm --name "xxxx" --run start(xxxx是服务器当前项目文件夹的名称),执行完可以查看项目处于“online”状态,说明在线的。

    9. 报错:PostCSS received undefined instead of CSS string

    报错原因:是因为node-sass、sass-loader的版本不对,或者因为某个插件使得这两个sass的相关插件没有成功安装上。

    10.配置运行的IP端口

    在package.json当中增加:

    {
       "config": {
        "nuxt": {
          "host": "0.0.0.0",
          "port": 8080(具体的项目端口)
        }
      },
    }
    

    11.部署报错:nuxt 使用nginx转发Uncaught SyntaxError: Unexpected token '<'

    转发的配置错误了,注释掉原来的index等信息,只需要proxy_pass http://127.0.0.1:8080

    12.关于pm2在windows环境下启动nuxt报Created by npm, please don‘t edit manually.问题

    报错原因:
    1、npm install node-cmd --save
    2、新建startscript.js

    const cmd=require('node-cmd'); 
    cmd.run('npm start');
    

    3、
    启动该脚本
    pm2 start startscript.js

    13.pm2的对应命令

    npm install pm2 -g  //安装
    pm2 update  //更新版本
    pm2 list    //显示所有进程状态
    pm2 monit   //监视所有进程
    pm2 log //显示所有进程日志
    pm2 stop all    //停止所有进程
    pm2 restart all //重启所有进程
    pm2 reload all  0 //秒停机重载进程 (用于 NETWORKED 进程)
    pm2 stop name   //停止指定的进程,name为标识
    pm2 restart name    //重启指定的进程,name为标识
    pm2 startup //产生 init 脚本 保持进程活着
    pm2 web //运行健壮的 computer API endpoint (http://localhost:9615)
    pm2 delete name //杀死指定的进程,name为标识
    pm2 delete all  //杀死全部进程
    

    14.nuxt 切换路由,页面回到顶部

    1、全局设置切换路由页面回到顶部

    在nuxt.config.js:中配置
    module.exports = {
      router: {
        scrollBehavior (to, from, savedPosition) {
          return { x: 0, y: 0 }
        }
      }
    }
    

    2、默认情况下,从当前页面切换至目标页面时,Nuxt.js 会让目标页面滚动至顶部。但是在嵌套子路由的场景下,Nuxt.js 会保持当前页面的滚动位置,除非在子路由的页面组件中将 scrollToTop 设置为 true;

    <template>
      <h1>子页面组件</h1>
    </template>
    
    <script>
    export default {
      scrollToTop: true
    }
    </script>
    

    15.关于想要使用route当中的类似beforeEach功能的时候,需要自定义一个小插件,在plugin文件夹下:

    1、在plugins目录下创建文件route.js;

    export default ({ app }) => {
      app.router.afterEach((to, from) => {
        console.log(to.path)
      })
    }
    

    2、在nuxt.config.jsplugins数组增加‘~/plugins/route’;

    16.报错:'state' should be a method that returns an object in store/user.js

    报错原因:在nuxt的store中,写state需要使用方法,不能用对象
    正确写法如下:

    const state = () => ({
    //具体的state对象
    })
    

    17.报错:Callback-based asyncData, fetch or middleware calls are deprecated. Please switch to promises or async/await syntax

    报错原因:没有加等待操作,具体修改后续更新;

    18.nuxt项目去除data-n-head=“ssr“默认属性

    在nuxt.config.js添加hooks配置

    hooks: {
        'render:route': (url, result) => {
          result.html = result.html.replace(/data-n-head=\"ssr\"/gi,'')
        }
      },
    

    19.nuxt默认的运行目录为static

    20.Nuxt项目网页源代码包含大量的css问题解决方案

    SEO过程中不利于查找有用信息,所以需要将css变成外部引入
    解决方案:
    修改nuxt.config文件,在build中增加一个配置,如下图:

    image.png

    21.关于子组件无法使用asyncData函数

    解决方案:在父组件(页面),先获取具体的数据,通过props传递到子组件即可。

    22. nuxtjs 将 window.__NUXT__ 内容合并到单独的文件中

    SEO的时候加上这个 window.__NUXT__内容太大了,需要缩减,为了避免出现其他的副作用,所以将这个内容移到单独的文件中进行引入;
    具体代码如下:
    nuxt.config.js

    import fs from "fs";
    import path from "path";
    
    export default {
      ...
    
      hooks: {
        "render:route": (url, page, context) => {
          const nuxtContent = page.html.match(/<script>(window.__NUXT__.+?)<\/script>/)[1];
          if (process.env.NODE_ENV !== "development") {
            const nuxtFilePath = path.join(process.cwd(), `.nuxt/dist/client/init.js`);````
            fs.writeFileSync(nuxtFilePath, nuxtContent);
           // page.html = page.html.replace(/<script>window.__NUXT__.+?<\/script>/, `<script src="/_nuxt/init.js?t=${new Date().getTime()}" defer></script>`); //注意这个defer延迟会引起网站访问无法返回,记得去掉这个延迟
          page.html = page.html.replace(/<script>window.__NUXT__.+?<\/script>/, `<script src="/_nuxt/init.js?t=${new Date().getTime()}"></script>`);
          }
        },
      },
    };
    

    23、使用viewport进行页面整体缩放

    1.在nuxt.config.js文件中增加

    export default {
    ...
      head: {
        meta: [
          { name: 'viewport', content: 'width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=no' },
        ],
        script: [
          {src: "/common.js", async: true}
        ]
      }
    ...
    }
    

    2.新建一个js文件(common.js)放在static中

    (function(){
        /*
        *HTML
         *原来的尺寸                            1800
         *要变成的尺寸(以开发正常样式的尺寸为基准)1920
         *比例                                  1800/1920
         */
        var curWidth = window.screen.width; //现在的电脑设备为1800px
        var targetWidth = 1920;
        var scale = curWidth/targetWidth;
        var meta = document.createElement("meta");
        meta.name = "viewport";
        meta.content = 'initial-scale='+scale+',minimum-scale='+scale+',maximum-scale='+scale+'';
        document.head.appendChild(meta);
    })();
    

    24、html模板修改,在根目录增加一个app.html,内容如下:

    <!DOCTYPE html>
    <html lang="" {{ HTML_ATTRS }}>
      <head {{ HEAD_ATTRS }}>
        {{ HEAD }}
      </head>
      <body {{ BODY_ATTRS }}>
        {{ APP }}
        <script>
          (function(){
              var curWidth = window.screen.width; //iphone 6plus为414px
              var targetWidth = 1920;
              if(curWidth<targetWidth){
                  var scale = curWidth/targetWidth;
                  document.body.style.zoom = scale;
              }
          })();
        </script>
      </body>
    </html>
    

    可以直接在html中修改信息,会直接更新到html上。

    25、nuxt的build输出目录

    export default {
    ...
      buildDir: 'nuxt-dist', //打包执行npm run build,会将原来的.nuxt中的内容输出到nuxt-dist目录。
    //注意:发布的时候一定要将内容放到.nuxt文件夹当中,否则无法发布成功。
    ...
    }
    

    后面内容会持续更新,有兴趣的小伙伴可以关注哦,比心~~

    相关文章

      网友评论

          本文标题:nuxt2踩坑记录

          本文链接:https://www.haomeiwen.com/subject/hzwyhdtx.html