在Vue中使用服务器端渲染时,异步数据更改
Async data change when using server side render in Vue
我想使用Vue在服务器端呈现,但模板内的内容数据必须从其他CMS服务器请求。
<template>
<h1>{{ content.heading }}</h1>
</template>
<script>
export default {
data() {
return {
content: {
heading: ''
}
}
},
created() {
axios
.get(CONTENT_RESOURCE)
.then(content => this.content = content);
}
}
</script>
由于axios.get
是异步请求,服务器将在请求完成之前发送空内容。
使用curl请求内容:
curl 'URL';
# It got <h1></h1>,
# but I want <h1>Something here</h1>
我如何确保它可以在服务器端呈现CMS内容数据?
根据veu -hackernews-2.0示例,src/server-entry.js将检测当前路由组件中的preFetch
功能。
因此,只需在当前路由组件中添加preFetch
功能,并将数据保存到Vuex存储。
<template>
<h1>{{ content.heading }}</h1>
</template>
<script>
const fetchContent = store =>
axios
.get(CONTENT_RESOURCE)
.then(content => store.dispatch('SAVE_CONTENT', content));
export default {
computed: {
content() {
return this.$store.YOUR_CONTENT_KEY_NAME
}
},
preFetch: fetchContent, // For server side render
beforeCreate() { // For client side render
fetchContent(this.$store);
}
}
</script>
您必须在代码中做以下更改:
var demo = new Vue({
el: '#demo',
data:{
content : {heading: ""}
},
beforeMount() {
var self = this;
setTimeout(function(){
self.content.heading = "HI"
}, 100)
}
})
相关文章:
- 在我的案例中,如何获取异步数据
- 使用从内部函数返回的异步数据对外部函数返回promise
- 异步数据加载后提交HTML表单的正确方法是什么
- jQuery Mobile Multi-Select from 异步数据
- AngularJS在控制器之间共享异步数据
- 反应.js - 处于异步数据状态的深层对象不起作用
- HighCharts导航器,用于在异步数据加载后保持范围.(懒惰加载)
- Angular2 模板尝试在异步数据存在之前访问它
- 根据异步数据计算的可观察量
- 节点.js使用异步数据进行响应
- 更改角度方向的异步数据
- 全局变量和异步数据
- angularjs中的异步数据检索
- JavaScript/jQueryAJAX-将异步数据返回到同步程序中
- Ember-嵌套视图中的异步数据
- Angular JS ng用异步数据重复
- 异步数据检索和缓存
- Angular,在得到异步数据之前停止渲染
- 在Vue中使用服务器端渲染时,异步数据更改
- highcharts中的异步数据输入