this.items.slice is not a function

Total
2
Shares

Hi I am learning vue with vuetify and I am trying to get users from backend api with Axios.

The problem is that I am getting this.items.slice is not a function error

This is what I tried inside my index.vue page


<script>
  /* import { Items as Users } from '@/api/user' */

  export default {
    data() {
      return {
        search: '',
        users:[],
        complex: {
          selected: [],
          headers: [
            {
              text: 'Avatar',
              value: 'avatar'
            },
            {
              text: 'Name',
              value: 'name'
            },
            {
              text: 'Email',
              value: 'email'
            },
            {
              text: 'Phone',
              value: 'phone'
            },
            {
              text: 'Action',
              value: ''
            }
          ]
          /* items: Users */
        }
      }
    },
    async asyncData({ $axios }) {
      const users= await $axios.$get('http://localhost:3333/api/users')
      return { users}
    }
  }
</script>

I am expecting to get users in table, I have check the api in postman and I get the correct response with all users.


Solution

Firstly, remove users from your data function:

export default {
    data() {
      return {
        search: '',
        // users:[], delete this line
        complex: {
...

You shouldn’t have what you want asyncData to return in your data function. asyncData will put it there itself.

Then try your asyncData like this:

async asyncData () {
    let { data } = await axios.get('http://localhost:3333/api/users')
    return { users: data.users } //or however your 'data' comes back. Try console.log(data) to see.
  }

The way you are currently returning ‘users’ would be a more complex object than just the users data so you should change it to return only the information you want.

Leave a Reply

Your email address will not be published. Required fields are marked *