# 1.解决Vue3中使用reactive定义的响应式失效
# 2.统一管理组件数据
# 3.重置组件setup中的数据
# 示例:
```typescript
<template>
<div class='demo'>
<div>{{ str }}</div>
<div><button @click="add">str++</button></div>
<div><button @click="reset">重置属性</button></div>
</div>
</template>
<script lang='ts'>
interface demo {
str: string;
add: () => void;
reset: () => void;
}
import { reactive, toRefs, onBeforeMount, onMounted, getCurrentInstance, defineComponent, ComponentInternalInstance, ToRefs } from 'vue';
export default defineComponent({
name: 'demo',
props: [],
setup() {
const ctx: ComponentInternalInstance | null = getCurrentInstance();
console.log(ctx);
console.log('1-开始创建组件-setup');
onBeforeMount(() => {
console.log('2.组件挂载页面之前执行----onBeforeMount');
});
onMounted(() => {
console.log('3.-组件挂载到页面之后执行-------onMounted');
});
const initState = (): demo => {
return {
str: "1",
add: () => {
model.str += '-';
},
reset: () => {
resetState();
}
};
};
let model: demo = reactive(initState());
let data: ToRefs<demo> = toRefs(model);
let resetState = (): void => {
Object.assign(model, initState()); // 将新状态对象的属性分配到现有响应式对象
};
return {
...data,
resetState
};
}
});
</script>
<style lang='stylus' scoped>
</style>
```
# VsCode用户代码片段如下:
```json
{
"Print to console": {
"prefix": "vue3-ts",
"body": [
"<template>",
" <div class='$TM_FILENAME_BASE'></div>",
"</template>",
"",
"<script lang='ts'>",
"interface $TM_FILENAME_BASE {",
"}",
"import { reactive,toRefs,onBeforeMount,onMounted, getCurrentInstance,defineComponent,ComponentInternalInstance,ToRefs} from 'vue'",
"export default defineComponent({",
" name: '$TM_FILENAME_BASE',",
" props: [],",
" setup() {",
" const ctx:ComponentInternalInstance | null = getCurrentInstance()",
" console.log(ctx)",
" console.log('1-开始创建组件-setup')",
" onBeforeMount(() => {",
" console.log('2.组件挂载页面之前执行----onBeforeMount')",
" })",
" onMounted(() => {",
" console.log('3.-组件挂载到页面之后执行-------onMounted')",
" })",
" const initState = (): $TM_FILENAME_BASE => {",
" return {",
" };",
" };",
" const model:$TM_FILENAME_BASE = reactive(initState());",
" let data: ToRefs<$TM_FILENAME_BASE> = toRefs(model);",
" let resetState = (): void => {",
" Object.assign(model, initState()); // 将新状态对象的属性分配到现有响应式对象",
" }",
" return {",
" ...data,",
" resetState",
" }",
" }",
"})",
"</script>",
"<style lang='stylus' scoped>",
"</style>",
],
"description": "Log output to console"
}
}
```