组件中的 Vuejs3 反应数组

Vuejs3 reactive array in a component

我尝试在组件中使用反应数组。
它适用于对象,但不适用于对象数组。

数组更新时如何更新视图?

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>'
};
....

根据 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.

我建议将数组分配给反应参数中名为 value 的字段,就像您对 test 所做的那样:

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

然后使用 resources.value=someVal 更新该值。

两件事:

  • resources: Vue.reactive({value:[]}) 可以通过使整个商店响应来避免
  • data() 是一个本地副本,但你真的想要一个单一的真实来源(即商店),所以通过计算 属性 访问它(基本上是 Vuex 的工作方式)。
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>'
};