vue.js 在组件中使用React阵列

j0pj023g  于 7个月前  发布在  Vue.js
关注(0)|答案(4)|浏览(65)

我尝试在一个组件中使用一个React数组。它只对一个对象有效,而对一个对象数组无效。
如何在更新阵列时更新视图?

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

字符串

vddsk6oq

vddsk6oq1#

根据官方文件:

第一个月第一个月:

接受一个对象并返回原始对象的一个React代理。这等效于2.x的Vue.observable()
....
React式转换是“深层”的:它会影响所有的巢状属性。在ES 2015 Proxy架构的实作中,传回的Proxy相等原始对象。建议您以独占方式使用React式Proxy,避免依赖原始对象。
我建议将数组分配给reactive参数中的字段value,就像您对test所做的那样:

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

字符串
然后使用resources.value=someVal来更新该值。

hi3rlvi2

hi3rlvi22#

一个快速的方法

const resources = reactive([]);

// set resources
resources.length = 0;
resources.push(...items)

字符串

tcbh2hod

tcbh2hod3#

除了上面的答案之外,还有两种主要的方法来处理React式阵列
具有可变值的单个数组

const arr = reactive([])
arr.length = 0  // clear
arr.push(...items)

字符串
将数组引用更改为不可变值

const arr = ref([]) // equivalent to reactive({value:[]})
arr.value = ["Shiver", "me", "timbers"]


两者都将触发响应式更新

cunj1qz1

cunj1qz14#

两件事:

  • resources: Vue.reactive({value:[]})可以通过使整个商店React来避免
  • 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>'
};

字符串

相关问题