【Vue】Vue3 重置组件状态
11月22日 / 11月22日
在某些场景下,例如表单提交,经常会需要重置表单状态。可以通过以下的方式进行组件状态优雅重置。
xxx写法
1 2<template> 3 <div> 4 <div>{{ state.name }} - {{ state.age }}</div> 5 <div @click="resetState">reset ref</div> 6 </div> 7</template> 8 9<script setup> 10 import { reactive } from 'vue'; 11 12 const state = reactive({ 13 name: 1, 14 age: 2, 15 }); 16 17 function resetState() { 18 state.name = 1; 19 state.age = 2; 20 } 21</script>
Hook 封装
1import { ref, reactive } from 'vue'; 2 3function clone(value) { 4 return JSON.parse(JSON.stringify(value)); 5} 6 7export function useResettableRef(value) { 8 const initialValue = clone(value); 9 const state = ref(value); 10 11 const reset = () => { 12 state.value = clone(initialValue); 13 } 14 15 return [state, reset]; 16} 17 18export function useResettableReactive(value) { 19 const state = reactive(clone(value)); 20 21 const reset = () => { 22 Object.keys(state).forEach((key) => delete state[key]); 23 Object.assign(state, clone(value)); 24 } 25 26 return [state, reset]; 27}
Hook 使用
1 2<template> 3 <div> 4 <div>ref:{{ refState.name }} - {{ refState.age }}</div> 5 <div @click="resetRefState">reset ref</div> 6 7 <div>reactive:{{ reactiveState.name }} - {{ reactiveState.age }}</div> 8 <div @click="resetReactiveState">reset ref</div> 9 </div> 10</template> 11 12<script setup> 13 import { useResettableRef, useResettableReactive } from '@/hooks/index.js'; 14 15 const [refState, resetRefState] = useResettableRef({ 16 name: 1, 17 age: 2 18 }); 19 20 const [reactiveState, resetReactiveState] = useResettableReactive({ 21 name: 1, 22 age: 2 23 }); 24</script>
cd ..