Nuxt.JS实战指南:从入门到精通的练习之旅

  • Nuxt.JS实战指南:从入门到精通的练习之旅已关闭评论
  • 177 次浏览
  • A+
所属分类:Web前端
摘要

官网:https://www.nuxtjs.cn/
搭建Nuxt2-参考文献:https://blog.csdn.net/weixin_44198965/article/details/125408111


官网:https://www.nuxtjs.cn/
搭建Nuxt2-参考文献:https://blog.csdn.net/weixin_44198965/article/details/125408111

一、为什么用Nuxt

SEO:所搜引擎优化

1.1如何进行搜索引擎优化?

  • 多页面
  • Title、描述、关键字
  • 网站内容

1.2-预渲染

1.2.1-预渲染图解
Nuxt.JS实战指南:从入门到精通的练习之旅
1.2.2-如何使用?
(1)vue项目中按照prerender-spa-plugin

npm install prerender-spa-plugin -S

(2)vue.config.js进行配置

修改Title、描述、关键词:vue-mate-info
(1)下载

npm install vue-meta-info -S

(2)到页面组件中进行配置

metaInfo:{
title:"西瓜程序猿",
meta:[{
name:"关键词,西瓜程序猿",
content:"描述"
}]
}

1.2.3-预渲染总结

可以解决:
1.打包多页面
2.可以解决每个页面单独生成title、描述、关键词
3.解决数据是在html生成放在页面上的,爬虫可以抓取到内容。

存在的问题:
1.预渲染无法配置动态路由
2.如果title、描述、关键词来与接口的数据,配置到met-info也是不行的。

适合做什么项目:
1.一个项目可以某几个页面要做SEO

1.3-服务端渲染(通过SSR)

1.3.1-预渲染图解
Nuxt.JS实战指南:从入门到精通的练习之旅
1.3.2-服务端渲染总结

适合做什么项目:
1.一个项目可能所有页面要做SEO(博客、内容网站)

1.4-优势劣势总结

1.前后端不分离
压力在后端
好处:安全

2.前后端分离
2.1-SPA单页面应用[vue-cli本身处理不了SEO]
压力在客户端

2.2预渲染
压力在客户端
问题:
1.在heml页面加载之前数据过来渲染后才有html的DOM结构,这样的话可能会存在一定时间空白页面的情况。
2.一个项目不是所有页面都做SEO。

2.3-服务器渲染
压力在客户端
问题:启2个服务[一个是后端自己的语言服务(C#/Java),一个是Node.JS的服务]

二、Nuxt安装与使用

2.1-安装与创建

2.1.1- 确保安装了 npx(npx 在 NPM 版本 5.2.0 默认安装了):

npm -v
npx -v

Nuxt.JS实战指南:从入门到精通的练习之旅

2.1.2. 创建一个Nuxt项目
(1)输入命名进行创建。

npx create-nuxt-app <项目名>

(2)选择项:

Project name——项目名称
Programming language——程序设计语言
Package manager——包管理器
UI framework——UI框架
Nuxt.js modules——NuxtJS模块(如果需要安装某个需要按"空格"电亮才行)
Linting tools——代码校验工具
Testing framework——测试框架
Universal——渲染模式(SSR:服务端渲染、SSG:静态页面生成)
Deployment target——部署目标
Development tools——开发工具
What is your GitHub username?——GitHub名称
Version control system——版本控制工具

演示如下:
Nuxt.JS实战指南:从入门到精通的练习之旅
创建成功如下如:
Nuxt.JS实战指南:从入门到精通的练习之旅

2.2-目录结构(VueCli 与 Nuxt 对比)

pages——页面(类似于:src/views)
components——组件(类似于:src/components)
static——静态资源(类似于:scr/assets)
store——vuex状态树(类似于:src/store)
muxt.config.js——全局配置文件(类似于:vue.config.js)

如下:
Nuxt.JS实战指南:从入门到精通的练习之旅

2.2-服务端生命周期

2.1.1-nuxtServerInit(store,context){}
参数1:vuex上下文
参数2:nuxt上下文

2.1.2-middleware()

全局:
全局导航守卫export default function(){    console.log("middleware kimi")}

局部:
第一种页面级别导航守卫  middleware:"kimi", 
第二种页面级别导航守卫  // middleware()

2.1.3-validate({params,query}){}
判断URL参数是否符合标准,页面中写。

validate({params,query}){
校验参数
...
console.log("3.validate...")
returntrue;
}

2.1.4-asyncData()——限于页面组件

会在这个里面做发送请求的操作。

2.1.5-fetch

fetch 方法用于在渲染页面前填充应用的状态树(store)数据, 与 asyncData 方法类似,不同的是它不会设置组件的数据。

2.2-服务端与客户端共有的生命周期

beforeCreate(){
console.log("6.beforeCreate")
},
created(){
console.log("7.created...")
},

2.3-客户端生命周期

beforeMount(){
console.log("8.客户端beforeMount...")
},
mounted(){
console.log("9.客户端monted...")
},
beforeUpdate(){
console.log("10.beforeUpdate...");
},
updated(){
console.log("11.updated...");
},
beforeDestroy(){
console.log("12.beforeDestroy...");
},
destroyed(){
console.log("13.destroyed...");
}

2.4-Nuxt路由

2.4.1-路由跳转的三种方式

a连接的形式跳转

Link的方式

<button @click="toList">js跳转

toList(){
this.$router.push({
path:'/list',
query:{
id:123
},
params:{
id:321
}
});
}

2.4.2-使用已有的VueCli路由文件
(1)安装插件。

npm install @nuxtjs/router -S

(2)在【nuxt.config.js】文件的【modules】模块中配置。

modules: [
'@nuxtjs/router'
],

(3)在根路径删新建一个【router.js】文件,文件名必须为router。
Nuxt.JS实战指南:从入门到精通的练习之旅
(4)修改该文件的内容。

importVuefrom"vue" importVueRouterfrom"vue-router" importHomefrom"@/pages/haverouter/Home.vue" importAboutfrom"@/pages/haverouter/About.vue" importNewsfrom"@/pages/haverouter/News.vue" Vue.use(VueRouter) const routes=[   {     path:'/home',     name:"Home",     component:Home   },   {     path:'/about',     name:"About",     component:About   },   {     path:'/news',     name:"News",     component:News   } ] letrouter=newVueRouter({   mode:"history",   routes }); //全局导航守卫 router.beforeEach((to,from,next)=>{   if(to.name=="About"){     next("/news")   }else{     next()   } }) exportfunctioncreateRouter(){   returnrouter; } 

Nuxt.JS实战指南:从入门到精通的练习之旅

2.5-Nuxt导航守卫

2.5.1-router.js

vue-cli中怎么用,next中就怎么用,几乎一样。

//全局导航守卫 router.beforeEach((to,from,next)=>{   if(to.name=="About"){     next("/news")   }else{     next()   } }) 

2.5.2-NuxtJS

中间件:middleware

全局: // 全局导航守卫 export default function(store,route,redirect,parms,query,req,res){       console.log("middleware kimi") }  局部: //第一种页面级别导航守卫   middleware:"kimi",   //第二种页面级别导航守卫   middleware(){     console.log("我是全局导航守卫")  } 

插件:plugins

(1)在【nuxt.config.js】的plugins进行配置。

plugins: [
'~/plugins/router.js'
],

(2)新建一个【router.js】文件,然后进行配置。
Nuxt.JS实战指南:从入门到精通的练习之旅

exportdefault ({app})=>{
全局
app.router.beforeEach((to,from,next)=>{
console.log(to)
next();
})
}

2.5.3-使用本地存储

服务端不能使用localStorage和Cookie
需要使用以下模块:

(1)安装

npm install cookie-universal-nuxt -s

(2)在【nuxt.config.js】的【modules】引入

modules: [ 'cookie-universal-nuxt' ],

(3)如何使用

设置cookie:this.$cookies.set('token', 123456) 1
获取cookie:this.$cookies.get("token") 1
清除cookie:this.$cookies.remove('token')

三、Nuxt配置项

3.1-Head

全局在【nuxt.config.js】的[head]中定义。
Nuxt.JS实战指南:从入门到精通的练习之旅
局部在每个页面中定义,全局已有的可以不用在局部定义。
Nuxt.JS实战指南:从入门到精通的练习之旅

3.2-CSS

3.2.1-使用全局css
Nuxt.JS实战指南:从入门到精通的练习之旅

3.2.2-使用ElementUI
(1)下载。

npm i element-ui -S

(2)在根目录新建一个【plugins】文件夹中新建一个【element.js】文件。

importVuefrom"vue"
importElementUI from"element-ui"
Vue.use(ElementUI);

(3)在【nuxt.config.js】文件中进行配置。

  css: [     "element-ui/lib/theme-chalk/index.css"   ],    plugins: [     '~/plugins/element.js'   ], 

3.3-Model与数据交互

3.3.1-安装axios

方法一:
(1)安装:npm install @nuxtjs/axios -S
(2)在【nuxt.config.js】中配置:'@nuxtjs/axios'
方法二:
(1)安装:npm install axios -S

3.3.2-asyncData生命周期(方法)

pages目录中的页面组件才可以使用,components内的.vue文件不可以使用的。
asyncData中没有this。

3.3.3-fetch生命周期(方法)

fetch是有this的。

3.4-配置代理

(1)安装

npm install @nuxtjs/axios @nuxtjs/proxy -S

(2)在【nuxt.config.js】文件中配置。

  modules: [     '@nuxtjs/axios',     '@nuxtjs/proxy'   ],   axios:{     //是否可以跨域     proxy:true   },   proxy:{     '/api':{       target:"http://testapi.xuexiluxian.cn/",       pathRewrite:{         '^/api':''       }     }   }, 

四、Nuxt使用Vuex状态树

export const state = () => ({   counter: 0 })  export const mutations = {   increment(state) {     state.counter++   } }  

五、项目重构(V-Cli项目重构到Nuxt中)

5.1-路由配置

(1)安装

npm install @nuxt/router -S

(2)在【nuxt.config.js】文件中进行配置。

 modules: [    "@nuxtjs/router"  ], 

(3)把vue-cli中router文件拷贝到nuxt项目根目录中,并命名为【router.js】。
Nuxt.JS实战指南:从入门到精通的练习之旅
(4)然后修改这个文件。

import Vue from 'vue'; import Router from 'vue-router'; import Home from '@/pages/blog/home.vue';//博客首页  Vue.use(Router);  const routes = [   { path: '/',component: Home}, ];   export function createRouter(){   return new Router({     mode: "history",     routes,   }); } 

5.2-代理和扩展$axios解耦

(1)安装代理与axios。

npm install @nuxtjs/axios @nuxtjs/proxy -S

(2)在【nuxt.config.js】文件中进行配置。

modules: [     "@nuxtjs/axios",     "@nuxtjs/proxy"   ], 

(3)配置代理。

//开启代理   axios:{     proxy:true,   },   proxy:{     "/api":{       target:"http://xx.xx.xx.xxx:8081"     }   }, 

(4)创建一个【plugins】文件夹,并新建一个名为【axios.js】文件,配置如下:

export default ( {$axios} ) =>{     //请求拦截器     $axios.onRequest((config)=>{         console.log("请求拦截器...");         return config;     });      //异常拦截器     $axios.onRequest((error)=>{         console.log("异常拦截器...");     });      //响应拦截器     $axios.onResponse((response)=>{         console.log("响应拦截器...");         return response.data;     }); } 

(5)在【nuxt.config.js】文件中进行配置。

  plugins: [     "~/plugins/axios"   ], 

5.3-引入VueX和组件重构

(1)创建一个【store】文件夹并在里面新建一个【index.js】文件,内容如下。

import Vue from 'vue' import Vuex from 'vuex'  //使用Vuex Vue.use(Vuex)  import app from './modules/app' const store = () => new Vuex.Store({   //导入模块   modules:{     app,   } });  //导出 export default store; 

(2)创建一个【models】文件夹并在里面新建一个【user.js】文件,内容如下。

//【应用程序模块】 export default{   //单一状态树,UI可通过this.$store.state.user.*获得数据   state:{    },   // 唯一拥有更改内存数据的接口,不可进行异步操作   mutations:{    },   // 与mutation通讯,UI层写入内存数据的接口,可异步操作   actions:{       } }  

5.4-引入ElementUI(按需引入)

(1)安装

npm i element-ui -S
npm i -D babel-plugin-component

(2)新建一个【elementui-ui.js】放在【plugins】文件夹下。

import Vue from 'vue'; // 按需引入ElementUI import {     Pagination,     Dialog,     Autocomplete,     Dropdown,     DropdownMenu,     DropdownItem,     Menu,     Submenu,     MenuItem,     MenuItemGroup,     Input,     InputNumber,     Radio,     RadioGroup,     RadioButton,     Checkbox,     CheckboxButton,     CheckboxGroup,     Switch,     Select,     Option,     OptionGroup,     Button,     ButtonGroup,     Table,     TableColumn,     DatePicker,     TimeSelect,     TimePicker,     Popover,     Tooltip,     Breadcrumb,     BreadcrumbItem,     Form,     FormItem,     Tabs,     TabPane,     Tag,     Tree,     Alert,     Slider,     Icon,     Row,     Col,     Upload,     Progress,     Spinner,     Badge,     Card,     Rate,     Steps,     Step,     Carousel,     CarouselItem,     Collapse,     CollapseItem,     Cascader,     ColorPicker,     Transfer,     Container,     Header,     Aside,     Main,     Footer,     Timeline,     TimelineItem,     Link,     Divider,     Image,     Calendar,     Backtop,     PageHeader,     CascaderPanel,     Loading,     MessageBox,     Message,     Notification,     Avatar,     Scrollbar,     Empty,     Skeleton,     SkeletonItem } from 'element-ui';  Vue.use(Pagination); Vue.use(Dialog); Vue.use(Autocomplete); Vue.use(Dropdown); Vue.use(DropdownMenu); Vue.use(DropdownItem); Vue.use(Menu); Vue.use(Submenu); Vue.use(MenuItem); Vue.use(MenuItemGroup); Vue.use(Input); Vue.use(InputNumber); Vue.use(Radio); Vue.use(RadioGroup); Vue.use(RadioButton); Vue.use(Checkbox); Vue.use(CheckboxButton); Vue.use(CheckboxGroup); Vue.use(Switch); Vue.use(Select); Vue.use(Option); Vue.use(OptionGroup); Vue.use(Button); Vue.use(ButtonGroup); Vue.use(Table); Vue.use(TableColumn); Vue.use(DatePicker); Vue.use(TimeSelect); Vue.use(TimePicker); Vue.use(Popover); Vue.use(Tooltip); Vue.use(Breadcrumb); Vue.use(BreadcrumbItem); Vue.use(Form); Vue.use(FormItem); Vue.use(Tabs); Vue.use(TabPane); Vue.use(Tag); Vue.use(Tree); Vue.use(Alert); Vue.use(Slider); Vue.use(Icon); Vue.use(Row); Vue.use(Col); Vue.use(Upload); Vue.use(Progress); Vue.use(Spinner); Vue.use(Badge); Vue.use(Card); Vue.use(Rate); Vue.use(Steps); Vue.use(Step); Vue.use(Carousel); Vue.use(CarouselItem); Vue.use(Collapse); Vue.use(CollapseItem); Vue.use(Cascader); Vue.use(ColorPicker); Vue.use(Transfer); Vue.use(Container); Vue.use(Header); Vue.use(Aside); Vue.use(Main); Vue.use(Footer); Vue.use(Timeline); Vue.use(TimelineItem); Vue.use(Link); Vue.use(Divider); Vue.use(Image); Vue.use(Calendar); Vue.use(Backtop); Vue.use(PageHeader); Vue.use(CascaderPanel); Vue.use(Loading.directive); Vue.use(Avatar);//头像 Vue.use(Scrollbar);//滚动条 Vue.use(Empty);//空状态 Vue.use(Skeleton);//骨架屏 Vue.use(SkeletonItem);  //挂载Message Vue.prototype.$loading = Loading.service; Vue.prototype.$msgbox = MessageBox; Vue.prototype.$alert = MessageBox.alert; Vue.prototype.$confirm = MessageBox.confirm; Vue.prototype.$prompt = MessageBox.prompt; Vue.prototype.$notify = Notification; Vue.prototype.$message = Message; 

(3)在【nuxt.config.jf】配置。

  // 全局CSS: https://go.nuxtjs.dev/config-css   css: [     "element-ui/lib/theme-chalk/index.css"   ],       // 在呈现页面之前要运行的插件: https://go.nuxtjs.dev/config-plugins   plugins: [     "@/plugins/element-ui",   ],           // 生成配置: https://go.nuxtjs.dev/config-build   build: {     //按需引入ElementUI     transpile: [/^element-ui/],     babel: {       plugins: [         ['component',           {             libraryName: 'element-ui',             styleLibraryName: 'theme-chalk'           }         ]       ]     }   } 

六、项目上线

6.1-项目打包

(1)运行命令

npm run build

(2)将一下文件拷贝到服务器上 (根据自己项目文件存放情况选择) 。
Nuxt.JS实战指南:从入门到精通的练习之旅
(3)使用pm2启动

pm2 start

6.2-Nuxt发布IIS绑定域名

参考文献:
1.安装ARR:https://www.likecs.com/show-527252.html?sc=504
2.Nuxt.js-IIS发布部署:https://blog.csdn.net/cplvfx/article/details/113940057

一、在IIS7中使用ARR(Application Request Routing)反向代理虚拟目录到Nodejs站点

Nuxt.JS实战指南:从入门到精通的练习之旅
Nuxt.JS实战指南:从入门到精通的练习之旅
(2)将下载好的文件拷贝到服务器上,并双击安装(打开时间比较长,慢慢等就好了)。
Nuxt.JS实战指南:从入门到精通的练习之旅
Nuxt.JS实战指南:从入门到精通的练习之旅
(3)安装成功后,重新打开IIS,出现这个图标说明安装成功了。
Nuxt.JS实战指南:从入门到精通的练习之旅
(4)双击【 Application Request Routing Cache 】图标,然后点击【Server Proxy Settings】。
Nuxt.JS实战指南:从入门到精通的练习之旅
(5)勾选【Enable Setting】,然后点击【应用】。
Nuxt.JS实战指南:从入门到精通的练习之旅

二、添加站点
(1)右击【网站】,点击【添加网站】。
Nuxt.JS实战指南:从入门到精通的练习之旅
(2)填写基本信息。
Nuxt.JS实战指南:从入门到精通的练习之旅
(3)然后点击刚刚创建的项目,再双击【URL 重写】,点击【添加规则】。
Nuxt.JS实战指南:从入门到精通的练习之旅
Nuxt.JS实战指南:从入门到精通的练习之旅
选择【反向代理】
Nuxt.JS实战指南:从入门到精通的练习之旅
填写你原本用Node发布的Nuxt项目IP+端口即可,然后点击确定。
Nuxt.JS实战指南:从入门到精通的练习之旅

七、其他相关知识点

7.1-nuxt中使用cross-env配置环境变量

(1)使用命令安装依赖

npm i cross-env

(2)新建一个【env.js】文件,填写相关不同环境的配置信息。

export default {   // 开发环境   dev: {     NODE_ENV : 'development',     // Base URL     BASE_URL: 'http://xx.xx.xx.xxx:8081',     // Base API     VUE_APP_BASE_API: 'http://xx.xx.xx.xxx:8081'   },    // 测试环境   test: {     NODE_ENV : 'test',     // Base URL     BASE_URL: 'http://xx.xx.xx.xxx:8081',     // Base API     VUE_APP_BASE_API: 'http://xx.xx.xx.xxx:8081'   },    // 生产环境   prod: {     NODE_ENV : 'production',     // Base URL     BASE_URL: 'http://xx.xx.xx.xxx:8081',     // Base API     VUE_APP_BASE_API: 'http://xx.xx.xx.xxx:8081'   } } 

(3)在【package.json】中配置。

    "dev": "npm run dev:dev",     "build": "npm run build:dev",     "start": "npm run start:dev",     "dev:dev": "cross-env MODE=dev nuxt",     "build:dev": "cross-env MODE=dev nuxt build",     "start:dev": "cross-env MODE=dev nuxt start",     "dev:test": "cross-env MODE=test nuxt",     "build:test": "cross-env MODE=test nuxt build",     "start:test": "cross-env MODE=test nuxt start",     "dev:prop": "cross-env MODE=prod nuxt",     "build:prop": "cross-env MODE=prod nuxt build",     "start:prop": "cross-env MODE=prod nuxt start", 

(4)在【nuxt.config.js】中配置。

 import env from './config/env';      // 配置环境变量   env: {     MODE: process.env.MODE   },        // 代理   proxy:{     "/api":{       target:"http://xx.xx.xx.xxx:8081",//配置接口地址       target:env[process.env.MODE].VUE_APP_BASE_API,//配置接口地址       changeOrigin: true     }   },    

7.2-nuxt中使用svg-icon

(1)安装相关依赖

npm i svg-sprite-loader -D
npm i nuxt-svg-sprite-loader

(2)新建如下相关文件
Nuxt.JS实战指南:从入门到精通的练习之旅
【icon】放置svg文件
Nuxt.JS实战指南:从入门到精通的练习之旅
【index.js】

import Vue from 'vue'; import SvgIcon from '@/components/common/svg-icon'; // 导入SVG组件  // 全局注册 Vue.component('svg-icon', SvgIcon);  // 三个参数:引入资源的目录 是否需要便利子目录 匹配文件的规则 const req = require.context('./svg', false, /.svg$/); const requireAll = requireContext => requireContext.keys().map(requireContext); requireAll(req);  

(3)在【nuxt.config.js】中进行配置。

  plugins: [     '@/assets/icons'   ],        modules: [     ['nuxt-svg-sprite-loader', {       symbolId: 'icon-[name]'     }]   ], 

7.3-nuxt中使用cookie

官方地址:https://www.npmjs.com/package/cookie-universal-nuxt

(1)安装依赖

npm i --save cookie-universal-nuxt

(2)在【nuxt.config.js】中进行配置。

 modules: [     'cookie-universal-nuxt'   ], 

(3)使用

const cookieValObject = { param1: 'value1', param2: 'value2' }  // nuxt middleware——中间件 export default ({ app }) => {   app.$cookies.set('cookie-name', 'cookie-value', {     path: '/',     maxAge: 60 * 60 * 24 * 7   })   app.$cookies.set('cookie-name', cookieValObject, {     path: '/',     maxAge: 60 * 60 * 24 * 7   }) }  // client——客户端 this.$cookies.set('cookie-name', 'cookie-value', {   path: '/',   maxAge: 60 * 60 * 24 * 7 }) this.$cookies.set('cookie-name', cookieValObject, {   path: '/',   maxAge: 60 * 60 * 24 * 7 }) 

7.4-nuxt中使用代码高亮highlight.js插件

参考文献:
(1)https://blog.csdn.net/qq2754289818/article/details/126396101
(2)https://blog.csdn.net/weixin_41897680/article/details/124925222

(1)安装

npm install highlight.js

(2)在【plugins】文件下添加一个【highlight.js】文件。

import Vue from 'vue'; import hljs from 'highlight.js'; // 样式文件(我选的是atom-one-dark-reasonable样式 可以通过highlight.js/styles 选择其他css) import 'highlight.js/styles/atom-one-dark-reasonable.css';  // 挂载highlight Vue.directive('highlight', function (el) {   let element = el.querySelectorAll('pre');   element.forEach((block) => {     hljs.highlightBlock(block);   }); }); 

(3)在【nuxt.config.js】中引入。

  plugins: [     '@/plugins/highlight'   ], 

(4)在代码中使用

<div v-html='BlogArticleDetail.articleContent' v-highlight></div> 

7.5-nuxt中使用全局水印

参考文献:
(1)实现水印:https://www.h5w3.com/239642.html
(2)nuxt自定义全局方法:https://blog.csdn.net/xuelang532777032/article/details/78414187

(1) 在【plugins】文件夹里新增一个【watermark.js】文件(文件名可以自己取)。
Nuxt.JS实战指南:从入门到精通的练习之旅

import Vue from 'vue'; let watermarkObj = {};  /**  *  设置全局水印  *  @text == 水印内容  *  @sourceBody == 水印添加在哪里,不传就是body  * */ let idGlocal = 'watermark_id'; let setWatermarkGlocal = (text, sourceBody) => {   if (document.getElementById(idGlocal) !== null) {     document.body.removeChild(document.getElementById(idGlocal));   }    let can = document.createElement('canvas');   can.width = 500;   can.height = 200;    let cans = can.getContext('2d');   cans.rotate((-20 * Math.PI) / 180);   cans.font = '15px Vedana';   cans.fillStyle = 'rgba(0, 0, 0, 0.05)';   cans.textAlign = 'left';   cans.textBaseline = 'Middle';   cans.fillText(text, can.width / 20, can.height);    let water_div = document.createElement('div');   water_div.id = idGlocal;   water_div.style.pointerEvents = 'none';   water_div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat';   if (sourceBody) {     water_div.style.width = '100%';     water_div.style.height = '100%';     sourceBody.appendChild(water_div);   } else {     water_div.style.top = '3px';     water_div.style.left = '0px';     water_div.style.position = 'fixed';     water_div.style.zIndex = '100000';     water_div.style.width = document.documentElement.clientWidth + 'px';     water_div.style.height = document.documentElement.clientHeight + 'px';     document.body.appendChild(water_div);   } };  /**  *  添加全局水印  *  @text == 水印内容  *  @sourceBody == 水印添加在哪里,不传就是body  * */ watermarkObj.setGlocal = (text, sourceBody) => {   setWatermarkGlocal(text, sourceBody);   window.onresize = () => {     setWatermarkGlocal(text, sourceBody);   }; };  /**  *  删除全局水印  * */ watermarkObj.removeGlocal = () => {   if (document.getElementById(idGlocal) !== null) {     document.body.removeChild(document.getElementById(idGlocal));   } };  // 设置全局方法 var watermark = {   install(Vue) {     Vue.prototype.$watermark = {       // 设置全局水印       setGlocal: function (test, sourceBody) {         watermarkObj.setGlocal(test, sourceBody);       },       //  删除全局水印       removeGlocal: function () {         watermarkObj.removeGlocal();       },     };   }, };  Vue.use(watermark); 

(2)在【nuxt.config.js】中进行配置。

  plugins: [     { src: '@/plugins/watermark', ssr: false }   ], 

(3)在xx.vue文件中使用。
【全局使用】

  mounted() {     // 添加水印     this.$watermark.setGlocal('©滔滔程序猿');        },   beforeDestroy() {     // 删除水印     this.$watermark.removeGlocal();   }, 

【局部使用】(注意:局部使用记得外外层div设置宽高)

<template> <div ref="content" style="width: 500px;height: 500px;border: 1px solid #ccc;"> </template>  <script>  export default {      mounted() {       // 添加水印       this.$watermark.setGlocal('©滔滔程序猿',this.$refs.content);     },     beforeDestroy() {       // 删除水印       this.$watermark.removeGlocal();     },  } </script> 

7.6-nuxt中实现图片放大预览功能

参考文献:https://cloud.tencent.com/developer/article/2018946

(1)安装

npm install v-viewer

(2)在【plugins】文件夹里新增一个【viewer.js】文件(文件名可以自己取)。

import Vue from 'vue'; import Viewer from 'v-viewer' import 'viewerjs/dist/viewer.css'  Vue.use(Viewer); Viewer.setDefaults({   Options: {      'inline': true,      'button': true,      'navbar': true,      'title': true,      'toolbar': true,      'tooltip': true,      'movable': true,      'zoomable': true,      'rotatable': true,      'scalable': true,      'transition': true,      'fullscreen': true,      'keyboard': true,      'url': 'data-source'    } }); 

(3)在【nuxt.config.js】中进行配置。

  plugins: [     { src: '@/plugins/viewer', ssr: false }   ], 

(4)在xx.vue文件中使用。

<div class="markdown-body-box" v-viewer> <!-- 页面内容、图片等等 --> </div> 

效果:
Nuxt.JS实战指南:从入门到精通的练习之旅

7.7-nuxt中使用windiCSS

官网网站:https://vuejsexamples.com/windi-css-for-nuxt-js/

(1)安装

npm i nuxt-windicss -D

(2)在【nuxt.config.js】文件中配置

  buildModules: [     'nuxt-windicss'   ], 

(3)如果使用了TS可以进行配置。

    "types": [       "nuxt-windicss"     ]