当前位置:网站首页>学习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监控系统部署
- Distributed transaction management DTM: the little helper behind "buy buy buy"
- [C language] open the door of C
- How to get bytes containing null terminators from a string- c#
- Write a thread pool by hand, and take you to learn the implementation principle of ThreadPoolExecutor thread pool
- Put a lantern on the website during the Lantern Festival
- How to write a summary of the work to promote the implementation of OKR?
- Comparison between applet framework and platform compilation
- BUUCTF(3)
- Comprendre la méthode de détection des valeurs aberrantes des données
猜你喜欢
【Go基础】2 - Go基本语句
Common components of flask
zabbix 5.0监控客户端
University stage summary
Ecole bio rushes to the scientific innovation board: the annual revenue is 330million. Honghui fund and Temasek are shareholders
ZABBIX 5.0 monitoring client
1. Getting started with QT
Go h*ck yourself:online reconnaissance (online reconnaissance)
1. Kalman filter - the best linear filter
Conversion of yolov5 XML dataset to VOC dataset
随机推荐
谷歌官方回应:我们没有放弃TensorFlow,未来与JAX并肩发展
Introduction to sap commerce cloud B2B organization function
L1-028 judging prime number (10 points)
PHP converts seconds to timestamps - PHP
Practice (9-12 Lectures)
MySQL 数据库 - 函数 约束 多表查询 事务
一文了解數據异常值檢測方法
PCIe knowledge points -010: where to get PCIe hot plug data
L1-027 rental (20 points)
Jianmu continuous integration platform v2.2.2 release
How does dataframe calculate the average value of each row as another column
How to set multiple selecteditems on a list box- c#
墨者学院-PHPMailer远程命令执行漏洞溯源
Using the rate package for data mining
A method for detecting outliers of data
Const string inside function - C #
Ecole bio rushes to the scientific innovation board: the annual revenue is 330million. Honghui fund and Temasek are shareholders
Cannot click button when method is running - C #
Leetcode 146. LRU 缓存
Unity text superscript square representation +text judge whether the text is empty