【发布时间】:2019-06-26 17:48:58
【问题描述】:
我目前使用以下component.vue,但是,这使得它评估两次(一次在渲染服务器端时,一次在客户端上)并且因为它是随机的用户看到城市闪烁一秒钟(然后切换到另一个)。
防止这种情况最有效的方法是什么?
export default {
data(){
return {
cities: ["Rome", "Amsterdam", "Paris", "Berlin", "London", "Athens", "Madrid"],
city: ''
}
},
created(){
this.city = cities[Math.floor(Math.random()*cities.length)];
}
}
【问题讨论】:
-
可以在定义之前检查
this.city是否已经存在:this.city = this.city || cities[Math.floor(Math.random()*cities.length)]; -
谢谢,但我也无法让它以这种方式工作,现在它不会返回任何城市。
-
您确定是
cities而不是this.cities? -
其他,你可以试试
if (process.browser) this.city = cities[...] -
问题是我可以让它只在客户端执行,但我希望它只在服务器上运行(然后将页面传递给已经存在城市的客户端,而不需要客户端重新评估再次,导致另一个随机城市出现)
标签: vue.js vue-component nuxt.js