当前位置:网站首页>学习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)
边栏推荐
- 促进OKR落地的工作总结该如何写?
- 线性代数1.1
- 一文了解數據异常值檢測方法
- Moher college phpMyAdmin background file contains analysis traceability
- Laravel page load problem connection reset - PHP
- Would you like to go? Go! Don't hesitate if you like it
- Introduction to neural network (Part 2)
- Activiti常見操作數據錶關系
- PHP converts seconds to timestamps - PHP
- How to use MOS tube to realize the anti reverse connection circuit of power supply
猜你喜欢
PCIe knowledge points -010: where to get PCIe hot plug data
弈柯莱生物冲刺科创板:年营收3.3亿 弘晖基金与淡马锡是股东
Conversion of yolov5 XML dataset to VOC dataset
Preliminary study on temporal database incluxdb 2.2
Introduction to neural network (Part 2)
JVM -- class loading process and runtime data area
1、卡尔曼滤波-最佳的线性滤波器
时序数据库 InfluxDB 2.2 初探
【Go基础】1 - Go Go Go
NPM run build error
随机推荐
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
What are the work contents of operation and maintenance engineers? Can you list it in detail?
【性能測試】一文讀懂Jmeter
How to write a summary of the work to promote the implementation of OKR?
Div hidden in IE 67 shows blank problem IE 8 is normal
Take you to master the formatter of visual studio code
Comparison between applet framework and platform compilation
论文学习——基于极值点特征的时间序列相似性查询方法
Use preg_ Match extracts the string into the array between: & | people PHP
Convert datetime string to datetime - C in the original time zone
Figure guessing game
Preliminary study on temporal database incluxdb 2.2
Life planning (flag)
Difference between static method and non static method (advantages / disadvantages)
21个战略性目标实例,推动你的公司快速发展
One of the general document service practice series
Moher College webmin unauthenticated remote code execution
Leetcode 23. Merge K ascending linked lists
OKR vs. KPI figure out these two concepts at once!
Show server status on Web page (on or off) - PHP