当前位置:网站首页>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)
边栏推荐
- R language ggplot2 visualization: ggplot2 visualization grouping box diagram, place the legend and title of the visualization image on the top left of the image and align them to the left, in which th
- Figure guessing game
- [performance test] read JMeter
- Using the rate package for data mining
- Introduction to neural network (Part 2)
- How does dataframe calculate the average value of each row as another column
- Advanced MySQL: Basics (5-8 Lectures)
- Unity text superscript square representation +text judge whether the text is empty
- Use preg_ Match extracts the string into the array between: & | people PHP
- Comparison between applet framework and platform compilation
猜你喜欢
[gurobi] establishment of simple model
Linear algebra 1.1
The second session of the question swiping and punching activity -- solving the switching problem with recursion as the background (I)
Tri des fonctions de traitement de texte dans MySQL, recherche rapide préférée
Advanced MySQL: Basics (5-8 Lectures)
1. Qt入门
What does range mean in PHP
运动【跑步 01】一个程序员的半马挑战:跑前准备+跑中调整+跑后恢复(经验分享)
Thesis learning -- time series similarity query method based on extreme point characteristics
1、卡尔曼滤波-最佳的线性滤波器
随机推荐
@Role of pathvariable annotation
Oceanbase is the leader in the magic quadrant of China's database in 2021
ZABBIX 5.0 monitoring client
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
Introduction to neural network (Part 2)
21个战略性目标实例,推动你的公司快速发展
C#实现一个万物皆可排序的队列
Sort by item from the list within the list - C #
In the era of low code development, is it still needed?
[go basics] 2 - go basic sentences
Cannot click button when method is running - C #
Using the rate package for data mining
Difference between static method and non static method (advantages / disadvantages)
Comparison between applet framework and platform compilation
yolov5 xml数据集转换为VOC数据集
L1-030 one gang one (15 points)
PCIE知识点-010:PCIE 热插拔资料从哪获取
1. Kalman filter - the best linear filter
[gurobi] establishment of simple model
Chrome is set to pure black