Home  >  Q&A  >  body text

Convert Vue array to proxy object

I am new to Vue. While making this component, I ran into difficulty here.

I use the following code to make an AJAX request to the API which returns an array:

<script>
import axios from 'axios';
export default {
  data() {
    return {
      tickets: [],
    };
  },
  methods: {
    getTickets() {
      axios.get(url)
        .then((response) => {
            console.log(response.data) //[{}, {}, {}]
            this.tickets = [...response.data]
            console.log(this.tickets) //proxy object
          })
    },
  },
  created() {
    this.getTickets();
  }
};
</script>

The problem is, this.tickets is set to a Proxy object, not the Array I get from the API.

What am I doing wrong here?

P粉476046165P粉476046165386 days ago498

reply all(2)I'll reply

  • P粉071626364

    P粉0716263642023-09-17 16:44:31

    If you want responsive information, use toRaw https://vuejs.org/api/reactivity-advanced.html#toraw

    const foo = {}
        const reactiveFoo = reactive(foo)
        
        console.log(toRaw(reactiveFoo) === foo) // true

    Or if you don't want the ref wrapper to surround your information, use unref

    https://vuejs.org/api/reactivity-utilities.html#unref

    reply
    0
  • P粉203792468

    P粉2037924682023-09-17 12:47:42

    Items in data like your tickets are converted into observable objects. This is for responsiveness (automatic re-rendering of the UI and other features). This is expected, the returned object should work like an array.

    Check out the reactivity documentation as you need to interact with the array in a specific pattern or it won't update on the UI: https://v3.vuejs.org/guide/reactivity-fundamentals.html

    If you don't want responsiveness - maybe you never update tickets on the client side and just want to display them - you can use the Object.freeze() method on response.data.

    reply
    0
  • Cancelreply