语法
2023年05月28日
1.1 useImmer
- App.ts
- useImmer.ts
<template>
<div>
<input
type="text"
:value="obj.b.c.d"
@change="($event) => handleChange($event)"
/>
</div>
</template>
<script setup lang="ts">
import { useImmer } from "./combinatorial/useImmer";
const [obj, setObj] = useImmer({
a: "",
b: {
c: {
d: "",
},
},
});
const handleChange = (event: any) => {
const {
target: { value },
} = event;
setObj((draft: any) => {
console.log(draft)
draft.b.c.d = value;
});
console.log(obj.value.b.c.d)
};
</script>
import { produce } from "immer";
import { shallowRef } from "vue";
export function useImmer(baseState: any) {
const state = shallowRef(baseState);
const update = (updater: any) => {
console.log(state.value)
state.value = produce(state.value, updater);
};
return [state, update];
}
1.2 shallowRef + immer
<template>
<div>
<input type="text" :value="obj.b.c.d" @change="($event)=> handleChange($event)">
</div>
</template>
<script setup lang="ts">
import { produce } from 'immer';
import { shallowRef } from 'vue';
const obj = shallowRef({
a: "",
b: {
c: {
d: "",
},
},
})
const handleChange = (event: any)=>{
const { target: { value} } = event;
const objNew = produce(obj.value,(draft)=>{
draft.b.c.d = value;
});
obj.value = objNew;
console.log(event)
console.log(obj.value.b.c.d)
}
</script>