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

作者站长头像
站长
· 阅读数 15

问题:我使用 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 新增删除都是可以在页面中实时渲染出来的。

===============问题已解决:问题原因:修改 style 时传入的样式仅数字,没有带单位 px,导致无法实时在页面中渲染。

回复
1个回答
avatar
test
2024-07-02
modifyAttrs(id: string, attrs: Object) {
    const index = this.layerList.findIndex((item) => item.id === id);
    let item = this.layerList[index];
    for (let key in attrs) {
        if (attrs.hasOwnProperty(key)) {
            item.attrs[key] = attrs[key];
        }
    }
    attrsToStyle(item);
    this.layerList = [...this.layerList]; // 强制更新视图
},

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;
}
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容