a special compiler macros defineReactive
for vue3 script-setup
<template>
<div>{{a}}</div>
<div>{{b}}</div>
<div>{{c}}</div>
</template>
<script setup>
import { ref } from 'vue';
const a = ref(0);
const b = ref(1);
const c = ref(2)
c.value = 3
</script>
example 1:
<template>
<div>{{a}}</div>
<div>{{b}}</div>
<div>{{c}}</div>
</template>
<script setup>
const state = defineReactive({
a:0,
b:1,
c:2
})
state.c = 3 // no .value
</script>
<template>
<div>{{a}}</div>
</template>
<script setup>
import { ref } from 'vue'
const a = ref(1)
const b = ref(2)
</script>
example 2:
<template>
<div>{{a}}</div>
</template>
<script setup>
defineReactive({
a:1,
b:2
})
</script>
<template>
<div>{{a}}</div>
<div>{{b}}</div>
<div>{{c}}</div>
</template>
<script setup>
import { toRefs,reactive } from 'vue'
const state = reactive({
a:0,
b:1,
c:2
})
state.c = 3 // no .value
const {a,b,c} = toRefs(state)
</script>
<template>
<div>{{a}}</div>
</template>
<script setup>
import { toRefs,reactive } from 'vue'
const auto_identifier__v_5=reactive({
a:1,
b:2
})
const {a,b} = toRefs(auto_identifier__v_5)
</script>
yarn add vite-plugin-vue3-define-reactive
or
npm install vite-plugin-vue3-define-reactive
In your vite.config.js
:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import defineReactive from 'vite-plugin-vue3-define-reactive'
export default defineConfig({
plugins: [
defineReactive(),
vue()
],
})
Create a new file in your src folder and write this for type hints.
declare global {
const defineReactive:<T extends {
[key:string]:any
}>(obj:T)=>T
}
export {}
if before script-setup version
you write vue3 code like this:
import { toRefs,reactive } from 'vue';
<script>
setup(){
const state = reactive({
a:1,
b:2,
c:3
})
state.c = 7
const handleClick = ()=>{}
return {
...toRefs(state),
handleClick
}
}
</script>
this is helpful for refactor you project to script-setup
:
<script setup>
const state =defineReactive({
a:1,
b:2,
c:3
})
state.c = 7
const handleClick = ()=>{}
</script>