6 javascript vue.js vue-component vue-reactivity vuejs3
I\xe2\x80\x99m 将映射传递给组件,然后发回新值并更新映射。这会触发地图上的手表,但传递的旧值和新值是相同的。
\n在这种情况下,手表是否可以接收旧值?
\n(function() {\n\nconst ui = {\nsetup() {\n const map = reactive(new Map([\n [\'width\', 800],\n [\'height\', 400]\n ]));\n\n function onCompUpdate(evt) {\n console.log(map.get(\'width\'), map.get(\'height\'), evt[0], evt[1]);\nmap.set(\'width\', Number(evt[0]));\n map.set(\'height\', Number(evt[1]));\n }\n \n watch(map, (n,o)=>{\n console.log(n.get(\'width\'), n.get(\'height\'), \n o.get(\'width\'), o.get(\'height\'));\n });\n\n return { map, onCompUpdate };\n },\n};\n\nconst vueApp = createApp(ui);\n\nvueApp.component(\'base-input\', {\nprops: [\'some\' ], emits: [\'comp-update\'],\nsetup(props, { emit }) {\n\n let chars = ref(Array.from(props.some.values()).join(\',\'));\n\n function checkInput(val) {\n emit(\'comp-update\', val.split(\',\'));\n chars.value = val;\n }\n\n return { chars, checkInput };\n},\ntemplate: `<input type="text" spellcheck="false" :value="chars"\ninput="checkInput($event.target.value)"/>`\n});\n\nvueApp.mount(\'#vue\');\n\n})();\nRun Code Online (Sandbox Code Playgroud)\nHTML:
\n<div id="vue">\n <base-input :some="map" @comp-update="onCompUpdate($event)"></base-input>\n</div>\nRun Code Online (Sandbox Code Playgroud)\n\n
发生这种情况是因为对旧的和新的引用是相同的。这是一种解决方法。不要直接观察参考,而是观察参考的传播,这确实发生了变化。它必须在函数表达式内完成,因为传播不是反应性的:
watch(() => [...map], (nArray, oArray)=>{
const n = new Map(nArray);
const o = new Map(oArray);
console.log(n.get('width'), n.get('height'), o.get('width'), o.get('height'));
});
Run Code Online (Sandbox Code Playgroud)
由于展开将地图转换为数组,因此在手表内您可以将值转换回地图。
这是你更新的小提琴
| 归档时间: |
|
| 查看次数: |
5514 次 |
| 最近记录: |