在将现有的应用程序从Vue2移植到Vue3时,我遇到了一个令人惊讶的问题.

如何让Vue3监视"外部"数组以获取更改?

This worked perfectly fine in Vue2, but stopped working in Vue3:

<ul id="list">
    <li v-for="t in dataArray"> {{t}} </li>
</ul>

<script>
    var numbers = [1,2,3]; //this is my external array

    var app = Vue.createApp({
        data() { return { dataArray : numbers } } //bind Vue to my external array
    }).mount("#list");

    numbers.push(4); //UI not updating, but worked fine in Vue2

</script>

我知道我可以呼叫app.dataArray.push,或者呼叫$forceUpdate等,但有没有办法强制VUE只监视现有的数组?

我想更广泛的问题是:如何将Vue3绑定到任意的普通JS对象?对象可能太复杂而无法重写,也可能来self 无法控制的外部API.这在Vue2或Angular 中是微不足道的(与任何普通对象的双向绑定,无论它是否属于实例/组件)

附注:这看起来像是Vue3的一个巨大的突破性变化,在任何地方都没有提到.

UPDATE:

根据a@Dimava的回答,修复上述代码的最不痛苦的方法似乎是:

var numbers = [1,2,3]; //this is my external array
numbers = Vue.shallowReactive(numbers); //convert to a reactive proxy

推荐答案

您需要将您的数组设置为Reactive

import { reactive, ref } from 'vue'   
const numbers = [1,2,3];
const reactiveNumbers = reactive(numbers)
reactiveNumbers.push(4)

// or, if you will need to reassign the whole array
const numbersRef = ref(numbers)
numbersRef.value.push(4)
numbersRef.value = [3, 2, 1]

// or, in the old style, if you are old
const data = reactive({
  numbers: [1, 2, 3]
})
data.numbers.push(4)
data.numbers = [3, 2, 1]

?(或者ShallowReactive,如果它包含许多出于性能原因不应该是react 性的大对象)

Vue.js相关问答推荐

Vue CDN的html工作,但v—如果不工作

元素不会对react 性props 的更改做出react

Vue Router中.getRoutes()获取的路由顺序优化建议

Vuejs - 更新数组中对象的数组

实现登录命令并访问 vuex 存储

即使响应为 200,也会调用 Axios Catch

正确实现 Vue.js + DataTables

在 SASS 中使用 Vuetify 类

Vue 3 - 带有全局组件的无法解析组件

使用vue.js单击时如何获取按钮的值

未捕获的类型错误:c.querySelectorAll 不是函数

如何让 Vue (vue cli 3) 正确处理 GraphQL 文件?

NUXT如何将数据从页面传递到布局

Vuejs 3 从子组件向父组件发出事件

Vuetify Jest 未知自定义元素

使用 nuxt,如何将路由名称放在页面标题中?

模块构建失败:错误:没有给出解析器和文件路径,无法在 nuxtjs 中推断出解析器

如何从组件内的单点捕获 vuejs 错误

Vue js在列表中添加动态字段,删除和排序不起作用

仅在提交时验证 vuetify 文本字段