gpt4 book ai didi

javascript - VueJS 2.0 服务端渲染 : How to get data only once using preFetch and beforeRouteEnter?

转载 作者:搜寻专家 更新时间:2023-10-30 22:39:11 25 4
gpt4 key购买 nike

为了测试 VueJS 服务器端渲染,我想弄清楚一些事情。我用过最新的 VueJS Hackernews 2.0作为我这个项目的样板。

目前我坚持这个:

服务器使用preFetch 预取数据。都好。当用户路由到此组件时,将在 beforeRouteEnter 函数内调用相同的函数。一切顺利。

但是,当用户第一次加载它时,preFetchData 函数会被调用 2 次。一次在 preFetch 中,一次在 beforeRouteEnter 中。

这是有道理的,因为这就是 Vue 路由器的工作方式。 preFetch 在服务器上运行,一旦 Vue 在客户端呈现,就会调用 beforeRouteEnter

但是,我不希望 Vue 在第一次加载时执行两次,因为数据已经从服务器端渲染函数 preFetch 存储在商店中。

我无法检查数据是否已在存储中,因为我希望该组件始终在 beforeRouteEnter 上进行 API 调用。只是当它来自服务器时第一次呈现时不是。

如何在这种情况下只获取一次数据?

  <template>
<div class="test">
<h1>Test</h1>
<div v-for="item in items">
{{ item.title }}
</div>
</div>
</template>

<script>
import store from '../store'

function preFetchData (store) {
return store.dispatch('GET_ITEMS')
}

export default {
beforeRouteEnter (to, from, next) {
// We only want to use this when on the client, not the server
// On the server we have preFetch
if (process.env.VUE_ENV === 'client') {
console.log('beforeRouterEnter, only on client')
preFetchData(store)
next()
} else {
// We are on the server, just pass it
next()
}
},
name: 'test',
computed: {
items () {
return this.$store.state.items
}
},
preFetch: preFetchData // Only on server
}
</script>

<style lang="scss">
.test {
background: #ccc;
padding: 40px;

div {
border-bottom: 1px red solid;
}
}
</style>

在上面:API 调用是在 store.dispatch('GET_ITEMS')

中完成的

最佳答案

我已经想通了一些事情。我将使用 from.name 检查用户来自哪里。如果这是 null,这意味着用户第一次加载页面,因为我命名了我所有的路由。所以我们知道我们正在为服务器呈现的 HTML 提供服务:

beforeRouteEnter (to, from, next) { 
if (from.name && process.env.VUE_ENV === 'client') {
preFetchData(store).then(data => {
next(vm => {
// do something
})
})
} else {
next()
}
}

关于javascript - VueJS 2.0 服务端渲染 : How to get data only once using preFetch and beforeRouteEnter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41586718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com