首页 文章

如何从Vuex上传数据?

提问于
浏览
2

我有Vuex存储,我存储'用户'(obj从服务器上传)

在创建部分的主App.vue中,我总是填写“用户”

这是异步方法 . 我的组件不要等待 . 当我在模板{}中使用时,我在控制台404中出错

http://example.net/images/undefined

但是在下一秒,当用户上传时,错误消失了 .

如何让应用等待在Vuex中上传异步日期?


更新 . 我明白为什么会这样 . 已安装组件,异步数据尚未就绪 . 我在Vuex中使状态'准备好',成功上传后它变成了现实 . 我在计算部分检查'准备好' . 如果没有准备好,则返回no_logo.png

但是,在我的组件中,在创建的部分中,当我从Vuex商店通过'user.id'从服务器获取其他数据时(但用户尚未准备好),我收到了错误 . 在获取之前如何在创建的部分中检查'ready'?

//html
<div id='app'>

  <ul>
    <li v-for='role in roles'>
      <p>{{role}}</p>
    </li>
  </ul>


</div>

//script Vue
var app = new Vue({
  el: '#app',
  data: {
    roles: []
  },

  created: {
    this.fetchingItems() //GOT ERROR need check Ready!!!
  },

  methods: {
    fetchingItems() {
      axios.get('api/getRoles/${this.$store.user.id}')
        .then((res) => this.roles = res.data.roles)
    }
  }
})


// This is store!!!.
const store = new Vuex.Store({
  state: {
    ready: false,
    user: {}
  },
  mutations: {
    USER_SET(state, user) {
        state.user = user
      },
      READY_SET(state) {
        state.ready = true
      }

  },
  action: {
    loadUser() {

  axios.get('api/getUser/${parseInt(localStorage.getItem('user_id'))}')
      commit('USER_SET', res.data.user)
      commit('READY_SET')

    }
  }
})

2 回答

  • 1

    会发生这种情况,因为安装组件时用户信息不存在,但最终会存在 .

    在此图像中,您将调度和操作,向Backend API询问数据,然后提交到商店 .

    enter image description here

    在提交之前,组件中的所有内容都不会填充实际数据 .

    您需要做的是使用 v-if 来显示或不显示组件 .

    其他方法是显示覆盖,直到所有数据加载如下:

    enter image description here

  • 1

    我修理它!

    用 Watch .

    watch: {
            ready: function () {
                this.fetchingItems()
            }
        },
    

相关问题