简体   繁体   English

nuxtjs:如何强制页面重新加载并调用 asyncData()?

[英]nuxtjs : how to force page reload and call asyncData()?

In my NuxtJS SSR project with bootstrap-vue as frontend:在我的 NuxtJS SSR 项目中,使用 bootstrap-vue 作为前端:

  1. I have some page with template and default component我有一些带有模板和默认组件的页面

  2. In component there is asyncData(context) function that makes some deal before component render and mounts在组件中有asyncData(context) function 在组件渲染和安装之前进行一些处理

Everything is working fine, except only one thing, I need reload (or refresh) a page after some interval automatically and call asyncData again.一切正常,除了一件事,我需要在一段时间后自动重新加载(或刷新)页面并再次调用asyncData Standard js window.location.reload() is not good solution, because it`s reloads fully page.标准 js window.location.reload()不是好的解决方案,因为它会重新加载整个页面。 I want refresh in vue style, when only changed components re-rendres.我想刷新 vue 风格,当只有更改的组件重新渲染时。 I tried to call $nuxt.refresh() but no any effect我试图调用$nuxt.refresh()但没有任何效果

Some code example (cut from real project ), page "index.vue":一些代码示例(从真实项目中截取),页面“index.vue”:

<template>
  <div>
  <b-tabs content-class="mt-3">
    <b-tab  title="Test" active><shdashboard searchtype="test"> </shdashboard></b-tab>
  
  </b-tabs>
</div>
</template>


<script>
export default {
  name : "index",
  async asyncData (context) {

if(process.server)
    {

    const host = "http://SOMEHOST";
    const http = context.$http;
    const data = await  http.$get(url);

    console.log('in server render')
  
     /* 
     some logic
     commit store and prepare data fot b-tab component

      */
     }
   },
methods : {

    refresh() {
         console.log("method refresh")
          this.$nuxt.refresh(); // Not any effect. 
                }
      },
  mounted() {
   console.log("page mounted");
   setInterval(()=>{

    /*
     I need to reload page every 15 sec, and call asyncData() to get new values for
      <b-tab> component
       
    */

    this.refresh();
   },15000);
}
</script>

What do I wrong?我错了什么?

One way, if I understand your issue correctly, is to use the Vuex store for storing whatever you are fetching in fetch / asyncData .如果我正确理解您的问题,一种方法是使用 Vuex 存储来存储您在fetch / asyncData中获取的任何内容。 That way you don't need to worry about the internals of Nuxt.js, and what hooks are triggered when.这样您就不必担心 Nuxt.js 的内部结构以及何时触发什么钩子。

Ie something like this:即是这样的:

export default {
  computed: {
    someData () {
      return this.$store.state.someData
    },
  },
  async asyncData ({ store, $axios }){

    let data = await $axios.$get(endpoint)
    store.commit('setSomeData', data)

  },
}

Then just use {{ someData }} in your template!然后在你的模板中使用{{ someData }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM