vue的服务端渲染ssr之nuxt.js

1、nuxt的安装

nuxt官网链接地址


//安装
 npx create-nuxt-app app
 
 npm i   // cnpm i
 
 cd app
 
 yarn run dev

2、了解nuxt的生命周期

fetch和asyncData在服务端和客户端是都有运行的,只不过运行过程中所处的环境问题,服务端中是没有windows对象存在的。

	//nuxt的部分生命周期是运行在服务端的比如 nuxtServerInit
	//在代码中会经常用到的fetch和asyncData 
	
	
	export default {
		asyncData() {
			console.log(window) // 服务端报错
		},
		fetch() {
			console.log(window) // 服务端报错
		},
		created () {
			console.log(window) // undefined
		},
		mounted () {
			console.log(window) // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
		}
}

nuxt的生命周期图

3、解决seo问题的关键文件

下面代码中的head,就是方便浏览器抓取和了解内容

const pkg = require("./package");

module.exports = {
  mode: "universal",

  /*
   ** Headers of the page
   */
  head: {      //类似html文件中的顶部方便浏览器执行的代码,可以自定义配置方便用户的搜索
    title: pkg.name,           
    meta: [
      { charset: "utf-8" },
      { name: "viewport", content: "width=device-width, initial-scale=1" },
      { hid: "description", name: "description", content: pkg.description }
    ],
    link: [{ rel: "icon", type: "image/x-icon", href: "/favicon.ico" }]
	//需要在head文件中引入文件可以使用下面的方法
	//script: [{ innerHTML: require('./assets/js/flexible'), type:'text/javascript', charset: 'utf-8'}],__dangerouslyDisableSanitizers: ['script']
  },

  /*
   ** Customize the progress-bar color
   */
  loading: { color: "#fff" },

  /*
   ** Global CSS
   */
  css: ["element-ui/lib/theme-chalk/index.css"],

  /*
   ** Plugins to load before mounting the App
   */
  plugins: ["@/plugins/element-ui", "@/plugins/router"],   //此处为插件的引入

  /*
   ** Nuxt.js modules
   */
  modules: ["@nuxtjs/axios"],

  axios: {
    proxy: true
  },
  proxy: {
    "/api/": "http://localhost:3001/"
  },

  /*
   ** Build configuration
   */
  build: {
    transpile: [/^element-ui/],

    /*
     ** You can extend webpack config here
     */
    extend(config, ctx) {}
  }
};

文件中所引用的插件都会在/plugins目录下,这里引用element-ui插件;在这里插入图片描述

//上面图片中第一个引用的js文件就是引入插件暴露到全局,下面是文件中的代码
import Vue from 'vue'
import Element from 'element-ui'
import locale from 'element-ui/lib/locale/lang/en'

export default () => {
  Vue.use(Element, { locale })
}

//引用的第二个文件是用来做路由拦截器的(所使用的就是vue的钩子函数),代码如下

export default ({app}) => {
  app.router.beforeEach((to,from,next)=>{
      console.log('我要去:'+to.path);
      
      next();
  })
};
//请求数据的拦截器可以用Axios
//使用Axios,并配置全局拦截器,处理跨域
//推荐使用@nuxtjs/axios、@nuxtjs/proxy,不需要在plugins配置:npm install @nuxtjs/axios @nuxtjs/proxy --save
//组件中使用axios:需要注意的是组件的fetch和asyncData里只能使用nuxtjs模板里的axios哦,如果使用我们自己引入的axios,是无法使用的

 /*
  ** Nuxt.js modules
  */
  modules: [
    '@nuxtjs/axios', // 不需要加入proxy
    '@nuxtjs/router'
  ],
  axios: {
    proxy: true
  },
  proxy: {
    '/api': {
      target: 'http://119.3.166.247:8080/',
      changeOrigin: true,
      pathRewrite: {
        '^/api': '/'
      }
    }
  },




//下面
export default {
  fetch ({ app }) {
    console.log(app.$axios)   //undefined
  },
  asyncData ({ app }) {
    console.log(app.$axios)		//undefined
  },
  created () {
    console.log(this.$axios)
  }
}



//plugins中配置全局拦截器可以参考下面代码

export default function (app) {
  let axios = app.$axios; 
 // 基本配置
  axios.defaults.timeout = 10000
  axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

  // 请求回调
  axios.onRequest(config => {})

  // 返回回调
  axios.onResponse(res => {})

  // 错误回调
  axios.onError(error => {})
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值