Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs3 reactive array in a component

I try to use reactive array in a component.
It's works with an object but not with an array of objects.

How to update the view when the array updated ?

var self = currentClassInstance // this

self.store = {
    resources: Vue.reactive([]),
    test:  Vue.reactive({ test: 'my super test' }),

    setResources(resources) {
        // this one doesn't update the view. ?
        this.resources = resources

    }, 
    setResources(resources) {
        // this one update the view
        this.test.test = "test ok"
    },  
}


....

const app_draw = {
    data() {
        return {
            resources: self.store.resources,
            test: self.store.test,
        }
    },
       
    updated() {
        // triggered for "test" but not for "resources"
        console.log('updated')
    },
       
    template: '<div v-for="(resource, key) in resources" :data-key="key">{{resource.name}}</div>'
};
....
like image 535
Pad Avatar asked Oct 18 '20 18:10

Pad


Video Answer


2 Answers

According to the official docs :

Reactive:
Takes an object and returns a reactive proxy of the original. This is equivalent to 2.x's Vue.observable()
....
The reactive conversion is "deep": it affects all nested properties. In the ES2015 Proxy based implementation, the returned proxy is not equal to the original object. It is recommended to work exclusively with the reactive proxy and avoid relying on the original object.

i suggest to assign the array to field called value inside the reactive parameter like you did with test :

resources: Vue.reactive({value:[]}),

then use resources.value=someVal to update that value.

like image 161
Boussadjra Brahim Avatar answered Oct 20 '22 01:10

Boussadjra Brahim


Two things:

  • resources: Vue.reactive({value:[]}) can be avoided by making the whole store reactive
  • data() is a local copy, but you really want a single source of the truth (i.e the store), so access it via a computed property (basically the way Vuex works).
var self = currentClassInstance // this

self.store = Vue.reactive({
  resources: [],
  setResources(resources) {
    this.resources = resources
  }, 
})

const app_draw = {

  computed: {
    resources() {
      return self.store.resources
    }
  }
       
  template: '<div v-for="(resource, key) in resources" :data-key="key">{{resource.name}}</div>'
};
like image 30
Ackroydd Avatar answered Oct 19 '22 23:10

Ackroydd