账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    vue一进入页面或者刷新页面调接口得到数据,但是却没有在页面上显示出来这是为什么呢?
    38
    0

    情景: 一进入首页就会调后台接口去数据库里查询有没有数据,如果有得到数据就把它显示在首页上。接口无报错,且数据能打印出来,但是首页就是没有展示数据,无论怎么刷新都不行,进入其他页面在返回时发现有数据了。怀疑与生命周期有关。
    一开始在首页的data()里面是这样定义username属性的:

    username: this.$store.state.user.username === '' ? '游客' : this.$store.state.user.username

    然后在mounted()里面diapatchstore里面的actions,在actions里面调接口并得到返回值,然后在mutations里改变state里面对应属性的值。但是值改变了,页面上的数据却没变。问题就在这里。无论怎么刷新都不管用!
    后来打开之前考下来的其他项目参考,发现它们在页面上的data()里面初始化的属性基本上都是没有值的。然后我便仿着来,同时在mounted()方法里加上了

    this.username = this.$store.state.user.username

    结果仍然没有。
    然后放弃了在actions里面调后台接口的想法,照着之前那位高仿饿了么的大神的写法在页面上直接调后台接口:

    getUserInfo(this.$store.state.user.userid).then(res => {
      console.log(res)
      if (res.data.success) {
        this.$store.state.user.username = res.data.data.username
        this.$store.state.user.phone = res.data.data.phone
        this.username = this.$store.state.user.username
      }
    })

    搞定了。
    至于原理我就有点不大了解了,只能来社区问了。一开始想着是不是生命周期的原因,但是我代码写在mounted()里面难道不比data()快?

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 甜蜜危机 普通会员 1楼

      在 Vue 中,如果你使用的是 Vue Router,那么数据获取失败后,页面可能无法立即加载新数据。这是因为 Vue Router 会等待新数据加载完成后再将数据添加到页面上。如果你想立即将新数据添加到页面上,可以使用 Vuex 或者懒加载来实现。

      1. Vuex:

      使用 Vuex 是一个 Vue 应用程序管理组件状态的常用方法。使用 Vuex 你可以将应用状态存储在一个单独的模块中,然后在需要的地方从这个模块中获取状态。当你需要获取状态时,可以调用 store.getters 函数来获取状态。例如:

      ```javascript import Vue from 'vue' import Vuex from 'vuex'

      Vue.use(Vuex)

      new Vue({ store: new Vuex.Store({ state: { data: null } }) }) ```

      在上述代码中,我们首先导入了 Vue 和 Vuex,然后创建了一个新的 Vue 应用程序。在应用程序的初始化阶段,我们创建了一个新的 Vuex store,并将数据初始化为 null。

      然后,在页面的 mounted 生命周期钩子中,我们可以使用 store.getters 函数来获取状态,并将数据添加到页面上:

      javascript new Vue({ el: '#app', store: new Vuex.Store({ state: { data: null } }) })

      1. 懒加载:

      懒加载是一种 Vue 技术,可以减少初次加载页面所需的时间。懒加载可以根据应用程序的状态动态地加载页面。例如,你可以设置一个函数来检查页面是否已经加载完成,如果已经加载完成,就直接返回数据,否则再加载页面:

      ```javascript import Vue from 'vue' import懒加载 from 'vue-lazyload'

      Vue.use(LazyLoad)

      new Vue({ el: '#app', data() { return { data: null } }, methods: { loadData() { // 获取数据 const data = '这是你的数据'; this.$store.dispatch('fetchData', data);

        // 如果数据已经加载完成,直接返回数据
        if (this.$store.state.data) {
          this.$store.dispatch('loadMoreData');
        }
      }
      

      } }) ```

      在上述代码中,我们首先引入了 Vue 和懒加载,然后创建了一个新的 Vue 应用程序。在应用程序的初始化阶段,我们调用了 fetchData 函数来获取数据,并将其发送到了 Vuex store。

      在页面的 mounted 生命周期钩子中,我们调用了 loadData 函数来加载数据。当数据加载完成时,我们调用了 loadMoreData 函数来加载更多的数据。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部