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

问题:
我使用 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,导致无法实时在页面中渲染。

阅读 6.5k
2 个回答
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;
}
新手上路,请多包涵

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

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

2、数组重新赋值

this.layerList[index] = item;
this.layerList = [...this.layerList];
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题