【问题标题】:How to display loaded data after page refresh in vue?vue中页面刷新后如何显示加载的数据?
【发布时间】:2019-01-12 00:47:12
【问题描述】:

我有一个包含一些项目的组件,这些项目是使用get request 方法从 api 加载的。当我点击一个项目时,我会使用动态路由重定向到它自己的页面:{ path: '/:id', component: Item }。使用currentItem() 方法识别单击的项目:currentItem() { this.items.find(item => item.code === this.$route.params.id) } 其中item.code 是我从api 获得的属性。 我的问题是,当我用当前项目刷新页面时,它不再加载。我尝试使用beforeCreate() 在他们自己的组件中再次加载项目。也许我可以使用watch 来根据项目更改状态?

beforeCreate() {
    this.$http.get(url).then(response => {
          this.items = response.body;
    }
},
watch: {
    '$route' (to, from) {
      this.currentItem()
    }
  }

这是demo

【问题讨论】:

    标签: javascript vue.js vue-resource


    【解决方案1】:

    您应该为$route 添加watch,以便在您在页面之间导航时对id 的更改做出反应。但在这种情况下,currentItem 有可能返回 null,因为您的请求将在 在调用 watch 处理程序之后结束。

    第一个解决方案是在Item 组件中监视items 集合,并在此监视处理程序中调用this.currentItem()。是的,您必须像在您的示例中一样在您的 Item 组件中加载 items

    如果可能的话,第二个是使用computed 属性currentItem 代替方法:

    computed: {
       currentItem() {
           return this.items.find(item => item.code === this.$route.params.id)
       }
    }
    

    这将是被动的,您不再需要观看。但是不要忘记将this.items默认设为空数组,以免出现null错误。

    第三个解决方案是结合第二个使用 Vuex store 在所有组件之间共享项目集合并执行以下操作:

    beforeCreate() {
        // you should check in this action that items already loaded earlier as well
        this.$store.dispatch('loadItems');
    },
    computed: {
       currentItem() {
           return this.items.find(item => item.code === this.$route.params.id)
       },
       items() {
           return this.$store.state.items
       }
    }
    

    商店:

    state: {
       items: [],
       itemsLoaded: false,
    }
    actions: {
       loadItems({state, commit}) {
          // avoid unnecessary loading between navigations
          if (itemsLoaded) return
          Vue.http.get('some url').then(response => {
              commit('setItems', response.body);
              commit('itemsLoaded');
          }
       }
    },
    mutations: {
       setItems: (state, items) => state.items = items 
       itemsLoaded: (state) => state.itemsLoaded = true
    }
    

    因此,例如,您不需要在 Item 和 Items 组件中存储项目。

    抱歉,帖子太长了。

    【讨论】:

    • 我确实使用 vuex 并分配了计算属性。 loadItems 操作应该是什么样的?
    • 您的第二个解决方案是我目前拥有的解决方案,但它不起作用。
    • @kabugh 在第二个解决方案中,您是否在 beforeCreate 挂钩中添加加载项?您可以更新问题以查看如何更改您的 Item 组件吗?我在答案中添加了商店示例。
    • 我也尝试使用 vuex 操作的解决方案,但仍然不起作用。
    • @kabugh 主要问题在于id 参数类型,您的项目有id 作为数字类型,但路由器返回字符串,并且您在产品组件中使用严格比较。使用parseInt(this.$route.params.id) 或者您可以将 id 作为来自路由器的预处理道具传递,请参阅router.vuejs.org/guide/essentials/…
    猜你喜欢
    • 1970-01-01
    • 2018-04-26
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    相关资源
    最近更新 更多