问题:
我使用 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); },