当前位置:网站首页>学习Nuxt.js
学习Nuxt.js
2022-07-04 08:08:00 【yibucuo】
理解SSR
传统服务端渲染CSR
单页面应用SPA 首屏性能不好 seo不好
服务端渲染SSR(server side render)
npm install vue-server-[email protected]2.6.11 express -D
在vue的脚手架项目中的vue-template-compiler 也是@2.6.11 上面的安装的版本号要和这里相同
已经存在spa
需要seo页面是否只是少数几个营销页面预渲染是否可以考虑
确实需要做ssr改造,利用服务器端爬虫技术puppeteer
最后选择重构 全新项目建议nuxt.js
npx create-nuxt-app <项目名>
运行项目: npm run dev
layouts/default.vue
nuxt-link像router-link
nuxt 像router-view
<template>
<div>
<nuxt-link no-prefetch to="/detail/123">详情</nuxt-link>//no-prefetch禁用预加载行为
<nuxt-link to="/cat">购物猫</nuxt-link>
<nuxt-link to="/">首页</nuxt-link>
<nuxt />
</div>
</template>
pages页面下自定义 选用哪个layouts
export default {
layout:'blank'
}
layouts/blank.vue
<template>
<nuxt></nuxt>
</template>
pages文件夹下新建.vue文件,自动创建路由,
nuxt的主页,也就是路由的路径为 / 的 就是pages/index.vue
<template>
<Tutorial/> //Tutorial组件 在components文件夹下的Tutorial.vue文件 无需导入直接使用Tutorial
</template>
middleware的使用
pages下某个文件使用 就是局部使用
export default {
middleware: ['auth']
}
nuxt.config.js中使用就是 全局配置 对每个
export default {
router: {
middleware: ['auth']
}
}
动态路由
访问localhost:3000/detail/123
pages/detail/_id.vue
<template>
<div>
{
{
$route.params.id}}//这里渲染123
</div>
</template>
async asyncData({
$axios, params, error }) {
// params就是上面的params
// asyncData出现的比较早 所以 不能访问this
if (params.id) {
// asyncData中不能使用this获取组件实例
// 但是可以通过上下文获取相关数据
const {
data: goodInfo } = await $axios.$get("/api/detail", {
params });
if (goodInfo) {
return {
goodInfo };
}
error({
statusCode: 400, message: "商品详情查询失败" });
} else {
return {
goodInfo: null };
}
}
路由拦截 路由扩展
extendRoutes(routes, resolve) {
routes.push({
name: 'custom',
path: '*',
component: resolve(__dirname, 'pages/404.vue')
})
},
插件
plugins/api-inject.js
export default ({
$axios }, inject) => {
inject('login', user => {
return $axios.$post('/api/login', user)
})
}
nuxt-config.js
plugins: [
'@/plugins/element-ui',
'@/plugins/api-inject',//注册下
]
this.$login(u) 就可以访问到api/login接口了
拦截器
plugins/interceptor.js
export default function ({
$axios, store }) {
$axios.onRequest(config => {
// 每次请求都会修改令牌的操作
if (store.state.user.token) {
config.headers.Authorization = "Bearer " + store.state.user.token;
}
return config;
});
}
nuxt.config.js
plugins: [
"@/plugins/interceptor"
],
跨域
nuxt.config.js
axios: {
proxy: true
},
proxy: {
"/api": "http://localhost:8080"
},
store
store/user.js
export const state = () => ({
token: ''
});
export const mutations = {
init(state, token) {
state.token = token;
}
};
export const getters = {
isLogin(state) {
return !!state.token;
}
};
export const actions = {
login({
commit, getters }, u) {
return this.$axios.$post("/api/login", u).then(({
token }) => {
if (token) {
commit("init", token)
}
return getters.isLogin;
});
}
};
在middleware和plugins下的js文件可以访问到user
export default function ({
store }) {
store.state.user.token
}
koa一半使用
var Koa = require('koa');
var app = new Koa();
const bodyparser = require('koa-bodyparser')
const router = require('koa-router')({
prefix:'/api'}) //通过/api/goods访问接口
app.keys = ["some secret", "another secret"]
const goods =[
{
id:1,text:'web全栈架构师',price:1000},
{
id:2,text:'java全栈架构师',price:1000},
]
router.get('/goods', ctx => {
ctx.body = {
ok: 1,
goods
}
})
router.get('/detail',ctx =>{
ctx.body = {
ok:1,
data:goods.find(good => good.id == ctx.query.id)
}
})
router.post('/login',ctx=>{
const user = ctx.request.body
if(user.username === 'jerry' && user.password == '123'){
const token = 'a mock token'
ctx.cookies.set('token',token)
ctx.body = {
ok:1,token}
}else{
ctx.body = {
ok:0}
}
})
app.use(bodyparser())
app.use(router.routes())
//使用路由中间件
// app.use(router.routes()).use(router.allowedMethods());
app.listen(8080)
边栏推荐
- ZABBIX monitoring system custom monitoring content
- Relations courantes de la fiche de données d'exploitation pour les activités
- [gurobi] establishment of simple model
- Group programming ladder race - exercise set l1-006 continuity factor
- ZABBIX 5.0 monitoring client
- 1、卡尔曼滤波-最佳的线性滤波器
- Leetcode 23. Merge K ascending linked lists
- Leetcode 146. LRU cache
- Activiti common operation data table relationship
- BUUCTF(3)
猜你喜欢
Common components of flask
Comparison between applet framework and platform compilation
Flask 常用组件
Email alarm configuration of ZABBIX monitoring system
University stage summary
Preliminary study on temporal database incluxdb 2.2
Oracle stored procedures and functions
【性能测试】一文读懂Jmeter
BUUCTF(4)
What does range mean in PHP
随机推荐
Wechat has new functions, and the test is started again
Moher College webmin unauthenticated remote code execution
Tri des fonctions de traitement de texte dans MySQL, recherche rapide préférée
Put a lantern on the website during the Lantern Festival
Node foundation ~ node operation
How to use MOS tube to realize the anti reverse connection circuit of power supply
Oracle stored procedures and functions
Cannot click button when method is running - C #
ZABBIX 5.0 monitoring client
ZABBIX monitoring system custom monitoring content
Take you to master the formatter of visual studio code
JVM中堆概念
Heap concept in JVM
MySQL 数据库 - 函数 约束 多表查询 事务
Convert datetime string to datetime - C in the original time zone
1. Getting started with QT
WordPress get_ Users() returns all users with comparison queries - PHP
University stage summary
力扣今日题-1200. 最小绝对差
Devops Practice Guide - reading notes (long text alarm)