简体   繁体   English

将 id 从 Vue 路由器参数传递到组件的 Vuex 调度

[英]Pass id from Vue router param to component's Vuex dispatch

I have backend Laravel API where i get我有后端 Laravel API 我得到

{
"id": 1,
"name": "Toni Stoyanov",
"email": "toni.nikolaev.23@gmail.com"
},

"id": 2,
"name": "Thomas Shelby",
"email": "st3851ba@gmail.com"
}
]

In my routes in Vue:在我的 Vue 路线中:

 {
  path: '/users/:id',
  component: UserDetails,
  props:true
},

I want to Display every single user for example with users/1 i want to get my first record from API.我想显示每个用户,例如 users/1 我想从 API 获取我的第一条记录。

In Vuex state i have:在 Vuex state 我有:

namespaced: true,
    state(){
        return{
            users: {
              
            }
        }
    },

getters:吸气剂:

getUsers(state){
        return state.users
    }

mutations:突变:

SET_USER(state, data){
        state.users = data
    }

and this action where i fetch all users:以及我获取所有用户的此操作:

async setUsers(context){
        let response = await axios.get('users/all')

        context.commit('SET_USER',response.data)
    }

In my DisplayUser.vue i have:在我的 DisplayUser.vue 我有:

props:['id'],
    data(){
        return{
            selectedUser: null
        }
    },
    created(){
       this.$store.dispatch('users/setUsers')

        this.selectedUser = this.$store.getters['users/getUsers'].find(user => user.id === this.id);
    },

First i dispatch my action to get data from API and after that in selectedUsers try to find the same id user..but in console i get首先,我调度我的操作以从 API 获取数据,然后在 selectedUsers 中尝试找到相同的 id 用户..但在控制台中我得到

this.$store.getters['users/getUsers'].find is not a function.

If i set in users static data everything works sometimes.如果我在用户 static 数据中设置,有时一切正常。 But when i fetch them from API no.但是当我从 API no. 获取它们时。

You're trying to access the getter before the http request has completed.您正在尝试在 http 请求完成之前访问 getter。 It should be enough to wait for the promise in created .created中等待 promise 应该就足够了。

The prop is a string道具是一个字符串

Also, the prop is coming as a string, so a === will not match.此外,道具以字符串形式出现,因此===将不匹配。 You can cast it to a Number(this.id) first:您可以先将其转换为Number(this.id)

Using .then syntax:使用.then语法:

created(){
  this.$store.dispatch('users/setUsers').then(res => {
    this.selectedUser = this.$store.getters['users/getUsers'].find(user => user.id === Number(this.id));
  });
}

Or using async/await syntax:或者使用async/await语法:

async created(){   // async keyword
  await this.$store.dispatch('users/setUsers')   // await this
  this.selectedUser = this.$store.getters['users/getUsers'].find(user => user.id === Number(this.id));
}

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

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