nuxt的理解

nuxt
nuxt允许将一部分vue的生命周期运行在服务端,在服务端生成部分渲染好的页面之后返回给客户端

nuxt和vue的生命周期

nuxt文档没有说明白服务端渲染中vue生命周期中的哪些部分是运行在服务端,哪些运行在客户端的…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<template>
<section class="container">
{{p}}
<br>
{{t}}
</section>
</template>

<script>
import axios from 'axios'
export default {
data () {
return {
p: 'p',
t: 't'
}
},
asyncData ({ req, params }) {
// We can return a Promise instead of calling the callback
return axios.get('https://api.ggemo.com/test')
.then((res) => {
return { posts: res.data }
})
},
created () {
this.p = this.posts.data.text
},
mounted () {
console.log("p before changed: ",this.p)
this.p = 'p mounted'
console.log("p changed: ",this.p)
this.t = 't mounted'
}
}
</script>

这样渲染出来的html文件的body部分为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<body data-n-head="">
<div data-server-rendered="true" id="__nuxt"><!---->
<div id="__layout">
<div>
header
<section class="container">
成功 successed
<br>
t
</section>
footer
</div>
</div>
</div>
<script>window.__NUXT__ = {
layout: 'default',
data: [{ posts: { status: 0, data: { text: '成功 successed' } } }],
error: null,
serverRendered: true
}</script>
<script src="/_nuxt/runtime.js" defer></script>
<script src="/_nuxt/pages_index.js" defer></script>
<script src="/_nuxt/pages_index.42262e91659a4eb99aae.hot-update.js" defer></script>
<script src="/_nuxt/vendors.app.js" defer></script>
<script src="/_nuxt/app.js" defer></script>
</body>

在页面上的渲染效果为
20190508134744.png

其中https://api.ggemo.com/test中的内容为{ posts: { status: 0, data: { text: ‘成功 successed’ } } }
created钩子中的 this.p的值,在传给客户端之前就已经被渲染进了html源码
mounted中的 this.p的值和this.t的值的更改是在客户端被执行的

由此可见,vue的created钩子运行在了服务端,mounted钩子运行在了客户端

nuxt官网的图片:
20190508135432.png
Render应该是执行vue生命周期中beforeMount之前的钩子