当前位置:网站首页>Learn nuxt js
Learn nuxt js
2022-07-04 08:11:00 【yibucuo】
understand SSR
Traditional server rendering CSR
Single page application SPA Poor first screen performance seo Not good.
Server rendering SSR(server side render)
npm install vue-server-[email protected]2.6.11 express -D
stay vue Of the scaffolding project vue-template-compiler It's also @2.6.11 The version number of the above installation should be the same as that here
Already exist spa
need seo Whether the page is just a few marketing pages, whether the pre rendering can be considered
It really needs to be done ssr reform , Using server-side crawler technology puppeteer
Finally, choose refactoring New project proposal nuxt.js
npx create-nuxt-app < Project name >
Run the project : npm run dev
layouts/default.vue
nuxt-link image router-link
nuxt image router-view
<template>
<div>
<nuxt-link no-prefetch to="/detail/123"> details </nuxt-link>//no-prefetch Disable preload behavior
<nuxt-link to="/cat"> Shopping cat </nuxt-link>
<nuxt-link to="/"> home page </nuxt-link>
<nuxt />
</div>
</template>
pages Customize under page Which to choose layouts
export default {
layout:'blank'
}
layouts/blank.vue
<template>
<nuxt></nuxt>
</template>
pages New under folder .vue file , Automatically create routes ,
nuxt The home page of , That is, the route path is / Of Namely pages/index.vue
<template>
<Tutorial/> //Tutorial Components stay components Under folder Tutorial.vue file Use directly without importing Tutorial
</template>
middleware Use
pages The next file uses It is local use
export default {
middleware: ['auth']
}
nuxt.config.js In use is Global configuration For each
export default {
router: {
middleware: ['auth']
}
}
Dynamic routing
visit localhost:3000/detail/123
pages/detail/_id.vue
<template>
<div>
{
{
$route.params.id}}// Render here 123
</div>
</template>
async asyncData({
$axios, params, error }) {
// params It's up there params
// asyncData It appears earlier therefore Cannot access this
if (params.id) {
// asyncData Cannot be used in this Get component instance
// But you can get the relevant data through the context
const {
data: goodInfo } = await $axios.$get("/api/detail", {
params });
if (goodInfo) {
return {
goodInfo };
}
error({
statusCode: 400, message: " Failed to query product details " });
} else {
return {
goodInfo: null };
}
}
Route blocking Routing extension
extendRoutes(routes, resolve) {
routes.push({
name: 'custom',
path: '*',
component: resolve(__dirname, 'pages/404.vue')
})
},
plug-in unit
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',// Under registration
]
this.$login(u) You can access api/login The interface
Interceptor
plugins/interceptor.js
export default function ({
$axios, store }) {
$axios.onRequest(config => {
// Each request modifies the token's operation
if (store.state.user.token) {
config.headers.Authorization = "Bearer " + store.state.user.token;
}
return config;
});
}
nuxt.config.js
plugins: [
"@/plugins/interceptor"
],
Cross domain
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;
});
}
};
stay middleware and plugins Under the js The file can be accessed to user
export default function ({
store }) {
store.state.user.token
}
koa Half use
var Koa = require('koa');
var app = new Koa();
const bodyparser = require('koa-bodyparser')
const router = require('koa-router')({
prefix:'/api'}) // adopt /api/goods Access interface
app.keys = ["some secret", "another secret"]
const goods =[
{
id:1,text:'web Full stack architect ',price:1000},
{
id:2,text:'java Full stack architect ',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())
// Using routing middleware
// app.use(router.routes()).use(router.allowedMethods());
app.listen(8080)
边栏推荐
- [gurobi] establishment of simple model
- zabbix 5.0监控客户端
- BUUCTF(4)
- Conversion of yolov5 XML dataset to VOC dataset
- This article is enough for learning advanced mysql
- Common components of flask
- Système de surveillance zabbix contenu de surveillance personnalisé
- How to send mail with Jianmu Ci
- Example analysis of C # read / write lock
- Devops Practice Guide - reading notes (long text alarm)
猜你喜欢
Chrome is set to pure black
NPM run build error
1. Kalman filter - the best linear filter
Famous blackmail software stops operation and releases decryption keys. Most hospital IOT devices have security vulnerabilities | global network security hotspot on February 14
Wechat has new functions, and the test is started again
Sqli labs download, installation and reset of SQL injection test tool one of the solutions to the database error (# 0{main}throw in d:\software\phpstudy_pro\www\sqli labs-...)
如何用MOS管来实现电源防反接电路
MySQL中的文本處理函數整理,收藏速查
How to improve your system architecture?
zabbix监控系统自定义监控内容
随机推荐
Ecole bio rushes to the scientific innovation board: the annual revenue is 330million. Honghui fund and Temasek are shareholders
The second session of the question swiping and punching activity -- solving the switching problem with recursion as the background (I)
时序数据库 InfluxDB 2.2 初探
Show server status on Web page (on or off) - PHP
With excellent strength, wangchain technology, together with IBM and Huawei, has entered the annual contribution list of "super ledger"!
yolov5 xml数据集转换为VOC数据集
Leetcode 23. Merge K ascending linked lists
Sports [running 01] a programmer's half horse challenge: preparation before running + adjustment during running + recovery after running (experience sharing)
1、卡尔曼滤波-最佳的线性滤波器
deno debugger
I was pressed for the draft, so let's talk about how long links can be as efficient as short links in the development of mobile terminals
Thesis learning -- time series similarity query method based on extreme point characteristics
运动【跑步 01】一个程序员的半马挑战:跑前准备+跑中调整+跑后恢复(经验分享)
学习Nuxt.js
Oracle stored procedures and functions
Take you to master the formatter of visual studio code
How to send mail with Jianmu Ci
What does range mean in PHP
促进OKR落地的工作总结该如何写?
Activiti common operation data table relationship