这里该文档仅展示了一种使用
观察整个反应对象的方法const state = reactive({
id: 1,
name: "",
});
watch(
() => state,
(state, prevState) => { // ...
}
);
如果我只想看
name
的变化怎么办?
watch(state.name, (name, prevName) => {
// for example: send a request to serve side for occupation validation
});
上面的代码是错误的。
您可以像这样观察单个属性的变化:
const state = reactive({
id: 1,
name: ""
});
watch(
() => state.name,
(newName, prevName) => {
/* ... */
}
);
watch: {
'state.name': function () {
// updated...
}
}
希望它对您有用。
观察对象属性的 getter。下面是使用
reactive()
和 ref()
声明对象的示例,使用 .value
声明对象时请注意 ref()
。
<script setup>
import { ref, reactive, watch } from 'vue'
const msg = ref('Hello World!')
const state1 = reactive({ id: 1, name: "your-name-reactive" })
const state2 = ref({ id: 2, name: "your-name-ref" })
const testingField1 = ref('')
const testingField2 = ref('')
const testingField3 = ref('')
watch(
() => state1.name,
(newName, prevName) => {
testingField1.value = newName
}
)
watch(
() => state2.value.name,
(newName, prevName) => {
testingField2.value = newName
}
)
watch(
[() => state1.name, () => state2.value.name],
() => {
testingField3.value = `was triggered by any one at ${new Date().toLocaleString()}`
}
)
</script>
<template>
<h1>{{ msg }}</h1>
<div>
<input v-model="state1.name" />
<button @click="state1.name = new Date().toLocaleString()">click me</button>
<span>{{ testingField1 }}</span>
</div>
<div>
<input v-model="state2.name" />
<button @click="state2.name = new Date().toLocaleString()">click me</button>
<span>{{ testingField2 }}</span>
</div>
<div>
<span>{{ testingField3 }}</span>
</div>
</template>