🧩 示例 1:打印修改前后数据
setData() 是异步的
Page({
data: {
count: 0
},
addCount() {
console.log('修改前 count =', this.data.count)
this.setData({
count: this.data.count + 1
})
console.log('修改后 count =', this.data.count)
}
})
2、基本写法(ref)
<script setup>
import { ref, nextTick } from 'vue'
const count = ref(0)
function addCount() {
console.log('修改前 count =', count.value)
count.value++
// 因为 Vue 的响应式更新是异步的
nextTick(() => {
console.log('更新完后 count =', count.value)
})
}
</script>
<template>
<view>
<text>当前计数:{{ count }}</text>
<button @click="addCount">+1</button>
</view>
</template>
3、对象类型(类似 setData({ 'user.name': xxx }))
<script setup>
import { reactive, nextTick } from 'vue'
const user = reactive({
name: '李姐',
age: 28
})
function updateUser() {
console.log('修改前 user =', JSON.stringify(user))
user.name = '小美'
user.age = 30
nextTick(() => {
console.log('修改后 user =', JSON.stringify(user))
})
}
</script>
<template>
<view>
<text>{{ user.name }}({{ user.age }}岁)</text>
<button @click="updateUser">更新用户</button>
</view>
</template>