vue3怎么使用reactive包裹数组正确赋值

其他教程   发布日期:2023年08月06日   浏览次数:606

本篇内容主要讲解“vue3怎么使用reactive包裹数组正确赋值”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“vue3怎么使用reactive包裹数组正确赋值”吧!

    使用reactive包裹数组正确赋值

    需求:将接口请求到的列表数据赋值给响应数据arr

    1. const arr = reactive([]);
    2. const load = () => {
    3. const res = [2, 3, 4, 5]; //假设请求接口返回的数据
    4. // 方法1 失败,直接赋值丢失了响应性
    5. // arr = res;
    6. // 方法2 这样也是失败
    7. // arr.concat(res);
    8. // 方法3 可以,但是很麻烦
    9. res.forEach(e => {
    10. arr.push(e);
    11. });
    12. };

    vue3使用

    1. proxy
    ,对于对象和数组都不能直接整个赋值。

    使用方法1能理解,直接赋值给用

    1. reactive
    包裹的对象也不能这么做。

    方法2为什么不行?

    只有push或者根据索引遍历赋值才可以保留reactive数组的响应性?

    如何方便的将整个数组拼接到响应式数据上?

    提供几种办法

    1. const state = reactive({
    2. arr: []
    3. });
    4. state.arr = [1, 2, 3]

    或者

    1. const state = ref([])
    2. state.value = [1, 2, 3]

    或者

    1. const arr = reactive([])
    2. arr.push(...[1, 2, 3])

    这几种办法都可以触发响应性,推荐第一种

    vue3的reactive重新赋值无效

    vue3官方的文档说明

    reactive() 返回一个对象的响应式代理

    所以 reactive 方法应该作用于一个对象Object,如果要使用数组,则需要包装一下:

    1. let list = reactive({
    2. data: [{id: 01, name: 'XXX'}]
    3. })

    或者使用 ref:

    1. let list = ref([{id: 1, name: 'Andy'}])

    已下引用原作者的代码:

    1. import { reactive, ref } from 'vue'
    2. export default {
    3. setup() {
    4. // 需要一个带默认值的数组list;
    5. let list = reactive([{id: 1, name: 'Andy'}])
    6. // 每次触发事件重置list,把新值放入,此种方式不会触发视图更新
    7. const checkBtn = () => {
    8. // 此时重置操作 地址指向变成一个新的地址,不会触发视图更新
    9. list = [{id: 1, name: 'Andy'}]
    10. list.push({id: 2, name: 'Lucy'})
    11. }
    12. // --------------------------------------------------
    13. // 正确的重置处理方法如下:使用reactive将数组包裹到一个对象中
    14. let list = reactive({
    15. data: [{id: 1, name: 'Andy'}]
    16. });
    17. const checkBtn = () => {
    18. list.data = [{id: 1, name: 'Andy'}]
    19. list.data.push({id: 2, name: 'Lucy'})
    20. }
    21. // 或者使用ref
    22. let list = ref([{id: 1, name: 'Andy'}]);
    23. const checkBtn = () => {
    24. list.value = [{id: 1, name: 'Andy'}]
    25. list.value.push({id: 2, name: 'Lucy'})
    26. }
    27. return {
    28. list,
    29. checkBtn
    30. }
    31. },
    32. }

    以上就是vue3怎么使用reactive包裹数组正确赋值的详细内容,更多关于vue3怎么使用reactive包裹数组正确赋值的资料请关注九品源码其它相关文章!