Convert Vue array to proxy object
P粉476046165
P粉476046165 2023-09-16 19:32:12
0
2
497

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粉476046165
P粉476046165

reply all(2)
P粉071626364

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

P粉203792468

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!