reactive
<template><div><h2 @click="increment">{{ count }}</h2></div>
</template><script setup lang="ts">
import { ref, onMounted } from 'vue'// 使用reactive创建响应式数据
const state = reactive({count: 0
})// 定义一个增加count的方法
const increment = () => {state.count++
}// 在组件挂载后输出初始化信息
onMounted(() => {console.log('组件已挂载')
})// 导出响应式数据和方法
export { state, increment }
</script><style>
/* 样式代码 */
</style>
在上述代码中,使用了reactive函数来创建一个响应式的state对象,其中包含一个count属性。还定义了一个increment方法,用于增加count的值。在组件挂载后,使用onMounted钩子函数输出了一个初始化信息。
最后,通过export关键字将state和increment导出,以便在模板中使用。
ref
<template><div><button @click="increment">Increment</button><p>Count: {{ count }}</p></div>
</template><script setup lang="ts">
import { ref } from 'vue';const count = ref(0);function increment() {count.value++;
}
</script><style scoped>
/* 样式代码 */
</style>
在这个例子中,使用了ref函数来创建一个响应式的变量count,并将其初始值设置为0。
然后,定义了一个increment函数,当按钮被点击时,会将count的值加1。
在模板中,展示了count的值,并提供了一个按钮来触发increment函数。