当前位置:网站首页>Nuxt. JS data prefetching
Nuxt. JS data prefetching
2022-07-01 15:54:00 【Black cat crimson】
The technical framework used in this paper is :
backstage :Express + MongoDb
The front desk :Vue2.js + [email protected]
stay Nuxt There are two ways to send a request in :
The scheme of separating the front and rear platforms ( The process of data to the page is completed in the browser ) There is no data in the web page source code
Foreground send request -> Server processing request -> Reception received data -> The foreground renders the data to the page
Usually through js The data obtained by the behavior of is separated from the front and back
Server side rendering scheme
- asyncData: Write it in the page component , Get the data in the page that needs to be rendered by the server , The data return To the page ( Use data directly on the page )
- nuxtServerInit: stay store/index.js It says in it , Always run on the server , It will only be executed once when the page is first loaded ( Suitable for writing some globally shared data )
- fetch: Write it in the page component , Get the data in the page that needs to be rendered by the server , Save the data to vuex ( Data sharing between parent and child components can be used preferentially fetch)
One 、asyncData
Send a request to get the data before loading the component , Render the data on the page in advance , Then the returned page will contain data .
- Because before the client creates the instantiation , therefore Out of commission this, The hook provides a parameter , You can get the context object (
{isDev, route, store, env, params, query, req, res, redirect, error}
etc. ), So as to do some simple operations . - Can only be used in the routing page component ( Every time you load a page, you call ), Invalid in custom component .
- The returned data will eventually match data Data merging , To ensure that page rendering errors do not occur , The return key should be in advance data In the statement ( If template The required attribute... Is not used in , There is no need to declare ).
1.1 An example
When we first open a website , The page will show Login immediately / register The words...
After successful login , This part will be replaced by
Now the need is , Display the user information on the page by rendering on the server
1.2 Preliminary analysis
When the user successfully logs in , Personal information can be saved to the server session in , That means , It seems that we can pass session Get user information .
router.post("/singin", async (req, res) => {
const {
username, password } = req.body;
const findUser = await User.findOne({
username, password });
// Login successful
if (findUser) {
// Personal information is saved to the server session in
req .session.user = findUser;
res.json({
code: 0,
msg: " Login successful "
})
}
// Login failed
else {
res.json({
code: -1,
msg: " Account or password error "
})
}
})
But ,session Save in server , What we need is to display data in the browser . obviously , The data in the server is not available in the browser .
There seems to be a problem with the bold text above , It seems to write an interface , Request through the interface when entering the home page session The data in seems to be ok , Try it .
1.2.1 code
request session Data interface :
router.get("/userInfo", (req, res) => {
if (req.session.user) {
res.json({
code: 0,
user: req.session.user,
msg: " User information obtained successfully "
})
}
else {
res.json({
code: 0,
user: null,
msg: " The current user is not logged in "
})
}
})
Foreground page :
import {
request } from "@/utils/request";
export default {
async asyncData() {
// After the encapsulation axios Request method
let result = await request.get("/users/userInfo");
console.log(result);
return {
result
}
},
};
1.2.2 test
After logging in on the homepage Refresh the page :
At this time, the data after login can be successfully displayed in the browser , Indicates that the user has logged in :
The server shows that the user is not logged in :
At this point, we need to analyze asyncData
The usage of this function .
asyncData It is possible to run in the browser , It may also run on the server .
When you refresh the page ,asyncData Method runs on the server , So the data message will be printed in the server , Through printing, we find that we can't get session data .
Routing jump <nuxt-link>
When ,asyncData Method runs in the browser , So the data message will be printed in the browser , By printing, we found that we can get session data .
Why are the printing positions different ,session The printing of data is also different ?
This is where session
Principle :
- After the user logs in through the interface , User information will be saved to the server session in
- session Inside will create cookie As a voucher , Then the interface returns the certificate to the browser for saving
- The browser will bring this next time it sends a request cookie voucher
therefore , The reason for the above problem lies in :
When the request is sent from the browser , The browser will carry it automatically session Corresponding cookie Send server , So the server can be based on cookie Get data
When the request is sent from the server , There is no session Corresponding cookie, So I can't get the login user information
Here I draw a picture to describe , It might be clearer :
In the above error operation , Our method is to call asyncData
Method , This method sends a request to the interface in the server , Instead of a request from a browser . because cookie Save in browser , So after the user logs in . The server shows that the user is not logged in .
In the second chapter, specific solutions are introduced .
Two 、nuxtServerInit
This method Only in vuex Use in , forever It will only run on the server , forever It is only executed once when the first screen is loaded
You can take two parameters :
- The first parameter is saved vuex Information
- The second parameter is the context object (context)
in other words , After the first screen is loaded , Whether through this.$router.push
still <nuxt-link>
Jump , This method will not execute , Unless refreshing the page again triggers loading .
It means , use nuxtServerInit
Acquired data , After the first screen is loaded, the data cannot be rendered to the page through the above two methods .
// The function responsible for login
submitForm() {
// Here we use Elemnet-ui Form validation method
this.$refs.loginForm.validate(async (valid) => {
// Form verification passed , You can send requests
if (valid) {
let result = await axios.post("/users/singin", {
username: this.ruleForm.name,
password: CryptoJS.MD5(this.ruleForm.pwd).toString(),
});
// adopt window.location.href = "/" Refresh the browser , At this point, you can render the data to the page
result.code === 0
// ? this.$router.push('/') Invalid
? (window.location.href = "/")
: (this.err = result.msg);
}
});
},
To write vuex:
import { request } from '@/utils/request'
export const state = () => ({
user: null,
})
export const mutations = {
SET_USER(state, payload) {
state.user = payload
}
}
export const actions = {
// Products are divided into front-end and back-end
// Adopted SSR The front end of can be divided into Front end client [ Concrete html page ] + Front end server
// there nuxtServerInit Running on the In the front-end server
// The second parameter of this method , You can get the context object of the server
// You can see from the documents , Here you can get nodejs When the server initiates the request req data
async nuxtServerInit({ commit }, { req }) {
const user = req.session.user;
commit("SET_USER", user)
}
}
Now back to the home page , take vuex Read out the data in :
<template>
<div>
<template v-if="user">
Welcome ,
<span class="username">{
{ user.username }}</span>
[<nuxt-link to="/exit"> sign out </nuxt-link>]
</template>
<template v-else>
<nuxt-link to="/login"> Login immediately </nuxt-link> |
<nuxt-link to="/register"> register </nuxt-link>
</template>
</div>
</template>
<script>
import { mapState } from "vuex";
export default {
computed:{
...mapState(['user'])
}
};
</script>
At this point, the data can be successfully rendered on the page .
3、 ... and 、fetch
This is just about v2.12 The following version
The method and asyncData almost , However, it cannot pass the data return
Return to page rendering .
If the page component is set fetch
Method , It will be called before each load of the component ( Before the server or switch to the destination route ).
fetch
The first parameter of the method is the context object of the page component context
, We can use fetch
Method to get the data and fill the state tree of the application . To make the acquisition process asynchronous , You need Return to one Promise,Nuxt.js Will wait for this promise Render components after completion .
Be careful : Cannot be used internally this
obtain Component instance ,fetch
Is in Before component initialization Called
such as :
<template>
<Son></Son>
</template>
<script>
export default {
fetch({ store, params }) {
return axios.get('/userList').then( res => {
store.commit('ADD_USER', res.data)
})
}
}
</script>
边栏推荐
- 远程办公经验?来一场自问自答的介绍吧~ | 社区征文
- Pico,是要拯救还是带偏消费级VR?
- 药品溯源夯实安全大堤
- Crypto Daily:孙宇晨在MC12上倡议用数字化技术解决全球问题
- TensorFlow团队:我们没被抛弃
- 智慧党建: 穿越时空的信仰 | 7·1 献礼
- HR interview: the most common interview questions and technical answers
- SAP S/4HANA: 一条代码线,许多种选择
- Samsung took the lead in putting 3nm chips into production, and Shanghai's fresh master students can settle directly. Nankai has established a chip science center. Today, more big news is here
- 2022 Moonriver全球黑客松优胜项目名单
猜你喜欢
Tensorflow team: we haven't been abandoned
C#/VB.NET 合并PDF文档
Crypto Daily:孙宇晨在MC12上倡议用数字化技术解决全球问题
Win11如何設置用戶權限?Win11設置用戶權限的方法
MySQL的零拷贝技术
[300 + selected interview questions from big companies continued to share] big data operation and maintenance sharp knife interview question column (III)
[target tracking] | template update time context information (updatenet) "learning the model update for Siamese trackers"
Stm32f411 SPI2 output error, pb15 has no pulse debugging record [finally, pb15 and pb14 were found to be short circuited]
电脑照片尺寸如何调整成自己想要的
精益六西格玛项目辅导咨询:集中辅导和点对点辅导两种方式
随机推荐
Hardware development notes (9): basic process of hardware development, making a USB to RS232 module (8): create asm1117-3.3v package library and associate principle graphic devices
Pocket Network为Moonbeam和Moonriver RPC层提供支持
Advanced cross platform application development (24): uni app realizes file download and saving
Deep operator overloading (2)
RT-Thread Env 工具介绍(学习笔记)
Automatique, intelligent, visuel! Forte conviction des huit conceptions derrière la solution sslo
ATSs: automatically select samples to eliminate the difference between anchor based and anchor free object detection methods
药品溯源夯实安全大堤
Task.Run(), Task.Factory.StartNew() 和 New Task() 的行为不一致分析
【LeetCode】43. String multiplication
July 1, 2022 Daily: Google's new research: Minerva, using language models to solve quantitative reasoning problems
Lean Six Sigma project counseling: centralized counseling and point-to-point counseling
6.2 normalization 6.2.6 BC normal form (BCNF) 6.2.9 normalization summary
MySQL高级篇4
Please, stop painting star! This has nothing to do with patriotism!
【Pygame实战】你说神奇不神奇?吃豆人+切水果结合出一款你没玩过的新游戏!(附源码)
Reading notes of top performance version 2 (V) -- file system monitoring
Pico,是要拯救还是带偏消费级VR?
GaussDB(for MySQL) :Partial Result Cache,通过缓存中间结果对算子进行加速
Tanabata confession introduction: teach you to use your own profession to say love words, the success rate is 100%, I can only help you here ~ (programmer Series)