我想在服务器端呈现中使用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内容数据进行呈现?
答案 0 :(得分:3)
根据vue-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>
答案 1 :(得分:0)
您必须在代码中进行以下更改:
var demo = new Vue({
el: '#demo',
data:{
content : {heading: ""}
},
beforeMount() {
var self = this;
setTimeout(function(){
self.content.heading = "HI"
}, 100)
}
})
这是一个有效的fiddle。