当前位置:网站首页>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)
边栏推荐
- Would you like to go? Go! Don't hesitate if you like it
- L1-021 important words three times (5 points)
- SQL注入测试工具之Sqli-labs下载安装重置数据库报错解决办法之一(#0{main}thrown in D:\Software\phpstudy_pro\WWW\sqli-labs-……)
- 真空介电常数和真空磁导率究竟是由什么决定的?为何会存在这两个物理量?
- 弈柯莱生物冲刺科创板:年营收3.3亿 弘晖基金与淡马锡是股东
- L1-024 the day after tomorrow (5 points)
- zabbix监控系统邮件报警配置
- Go h*ck yourself:online reconnaissance (online reconnaissance)
- Put a lantern on the website during the Lantern Festival
- Practice (9-12 Lectures)
猜你喜欢

弈柯莱生物冲刺科创板:年营收3.3亿 弘晖基金与淡马锡是股东

Introduction to neural network (Part 2)

PCIe knowledge points -010: where to get PCIe hot plug data

Easy to understand: understand the time series database incluxdb

zabbix监控系统自定义监控内容

Go h*ck yourself:online reconnaissance (online reconnaissance)

墨者学院-PHPMailer远程命令执行漏洞溯源

Moher College phpmailer remote command execution vulnerability tracing

Book list | as the technical support Party of the Winter Olympics, Alibaba cloud's technology is written in these books!

ZABBIX 5.0 monitoring client
随机推荐
Comprendre la méthode de détection des valeurs aberrantes des données
System architecture design of circle of friends
The second session of the question swiping and punching activity -- solving the switching problem with recursion as the background (I)
L1-025 positive integer a+b (15 points)
Parallel shift does not provide any acceleration - C #
Thesis learning -- time series similarity query method based on extreme point characteristics
Take you to master the formatter of visual studio code
This monitoring system can monitor the turnover intention and fishing all, and the product page has 404 after the dispute appears
[go basics] 2 - go basic sentences
yolov5 xml数据集转换为VOC数据集
如何用MOS管来实现电源防反接电路
L1-030 one gang one (15 points)
[go basics] 1 - go go
zabbix监控系统自定义监控内容
Tri des fonctions de traitement de texte dans MySQL, recherche rapide préférée
@Role of pathvariable annotation
Relations courantes de la fiche de données d'exploitation pour les activités
C#实现一个万物皆可排序的队列
【Go基础】1 - Go Go Go
Application of isnull in database query