You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.5 KiB

<template>
<h2>当前求和为{{ sum }}</h2>
<button @click="sum++">点击+1</button>
<hr>
<h2>当前信息为{{ msg }}</h2>
<button @click="msg+='!'">修改信息</button>
<hr>
<h2>姓名{{ person.name }}</h2>
<h2>年龄{{ person.age }}</h2>
<h2>薪资{{ person.job.j1.salary }}</h2>
<button @click="person.name+='~'">修改姓名</button>
<button @click="person.age++">修改年龄</button>
<button @click="person.job.j1.salary++">修改薪资</button>
<h2></h2>
</template>
<script>
import {reactive, ref, watch} from "vue";
export default {
name: 'Demo',
// watch: {
// // Vue2中的实现
// // sum(newValue, oldValue) {
// // console.log('sum的值变了', newValue, oldValue)
// // }
// // Vue2中的实现二
// // sum: {
// // immediate: true,
// // deep: true,
// // handler(newValue, oldValue) {
// // console.log('sum的值变了', newValue, oldValue)
// // }
// // }
2 years ago
// },
2 years ago
setup() {
let sum = ref(0)
let msg = ref('你好呀')
let person = reactive({
name: '张三',
age: 18,
job: {
j1: {
salary: 20
}
}
})
// 情况一:监视ref的所有定义的一个响应式
// watch(sum, (newValue, oldValue) => {
// console.log('sum值变化了', newValue, oldValue)
// }, {deep: true, immediate: true})
2 years ago
// 情况二:监视ref的所有定义的多个个响应式
watch([sum, msg], (newValue, oldValue) => {
console.log('sum和msg的值变化了', newValue, oldValue)
}, {immediate: true})
// 情况三:监控reactive所定义的一个响应式数据中的全部属性,注意:此处无法正确的获取oldValue,强制开启deep
// watch(person, (newValue, oldValue) => {
// console.log('person对象的值变了', newValue, oldValue)
// }, {deep: false})
// 情况四:监控reactive所定义的一个响应式数据中的某个属性
// watch(()=>person.age, (newValue,oldValue)=>{
// console.log('person.age对象的值变了', newValue, oldValue)
// })
// 情况五:监控reactive所定义的一个响应式数据中的某些属性
watch([() => person.name, () => person.age], (newValue, oldValue) => {
console.log('person.age和.name对象的值变了', newValue, oldValue)
2 years ago
})
// 特殊情况
watch(() => person.job, (newValue, oldValue) => {
console.log('person.job对象的值变了', newValue, oldValue)
}, {deep: true})
return {
sum,
msg,
person
}
}
}
</script>