#独家
vue3中修改数组对象的中的对象属性值页面如何更新?

2023-05-31 0 1,253

问题:
我使用 pinia 进行状态管理,写法大概如下,由于我修改的是数组中某个对象下的对象的属性,数组更新后,页面无法重新渲染。

// store/index.js
export const useLayerStore = defineStore("layer", {
    state: () => {
        return {
            layerList: [],
        };
    },
         actions: {
modifyAttrs(id: string, attrs: Object) {
            const index = this.layerList.findIndex((item) => item.id === id);
            let item = Object.assign(this.layerList[index]);
            item.attrs = { ...item.attrs, ...attrs };
            item = attrsToStyle(item);
            this.layerList[index] = item;
        },
    },
});

function attrsToStyle(obj: layerItem) {
    const { x, y, width, height } = obj.attrs;
    obj.style.left = x;
    obj.style.top = y;
    obj.style.width = width;
    obj.style.height = height;
    return obj;
}
// 组件的 js
import { useLayerStore } from "@/stores/";
const layer = useLayerStore();
const { layerList } = storeToRefs(layer);
<div class="editor-component-box">
            <component
                v-for="comp in layerList"
                :key="comp.id"
                :is="comp['component']"
                class="absolute component-item"
                :class="{ 'selected-border': comp.selected }"
                :style="comp['style']"
                @click="componentHandleClick(comp.id)"
                :data-id="comp.id" />
        </div>

当我点击按钮修改元素的 x,y,width,height 某个样式值的时候,layerList 中对应的元素的下的style对象的下属性值也会更新,由于页面是根据这个对象来渲染内联样式的, style 在手动更新后一直无法更新,想请教下各位大佬这是什么原因?
数组 layerList 新增删除都是可以在页面中实时渲染出来的。

数组里更新某项直接通过索引赋值不行,vue无法监测到变化
1、通过splice函数

this.layerList.splice(index, 1, item);

2、数组重新赋值

this.layerList[index] = item;
this.layerList = [...this.layerList];
modifyAttrs(id: string, attrs: Object) {
    const index = this.layerList.findIndex((item) => item.id === id);
    let item = this.layerList[index];
    item.attrs = { ...item.attrs, ...attrs };
    attrsToStyle(item);
},
收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

1. JK下载官网所有资源来源于开发团队,加入会员即可下载使用!如有问题请联系右下角在线客服!
2. JK下载官方保障所有软件都通过人工亲测,为每位会员用户提供安全可靠的应用软件、游戏资源下载及程序开发服务。
3. JK开发团队针对会员诉求,历经多年拥有现今开发成果, 每款应用程序上线前都经过人工测试无误后提供安装使用,只为会员提供安全原创的应用。
4. PC/移动端应用下载后如遇安装使用问题请联系右下角在线客服或提交工单,一对一指导解决疑难。

JK软件下载官网 技术分享 vue3中修改数组对象的中的对象属性值页面如何更新? https://www.jkxiazai.com/1766.html

JK软件应用商店是经过官方安全认证,保障正版软件平台

相关资源

官方客服团队

为您解决烦忧 - 24小时在线 专业服务