1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| <template> <div> <h2>Student组件</h2> <h2>计算属性-computed</h2><br/> <span>姓:</span><input type="text" v-model="person.firstName" /><br/> <span>名:</span><input type="text" v-model="person.lastName" /><br/> <span>爱好:{{person.hobby}}</span><br/> <span>全名:{{fullName}}</span><br/> <span>修改全名</span><input type="text" v-model="fullName" /><br/> <span>stu的Job </span>{{JSON.stringify(person.job)}} <hr /> <h2>监视属性-watch</h2><br/> <span>求和:{{sum}},信息:{{message}}</span><br/> <button @click="btnEdit">修改sum和message</button> <button @click="btnStuName">修改stu的姓名</button> <button @click="btnEditStuHobby">修改stu的爱好</button> <button @click="btnEditStuJobA">修改job中的a值</button> </div> </template> <script>
import {ref, computed, reactive,watch, watchEffect} from 'vue'; export default { name: 'Student', setup(props, context) { let sum = ref(0) let message = ref('消息') let person = reactive({ firstName: 'odin', lastName: 'sam', hobby: ['抽烟', '喝酒', '烫头'], job: { a:{x:1,y:2} } }) let btnEdit = function () { sum.value++; message.value+="~" } let btnStuName = function () { person.firstName += "!"; person.lastName += "~"; } let btnEditStuHobby = function () { person.hobby.push('学习') }
let btnEditStuJobA = function () { person.job.a.x += 10; }
let fullName = computed({ get() { return person.firstName + '-' + person.lastName; }, set(value) { person.firstName = value.split('-')[0]; person.lastName = value.split('-')[1]; } })
watch([sum, message], (newValue, oldValue) => { console.log('sum或message改变了',newValue,oldValue); }, { immediate: true }) watch([person], (newValue, oldValue) => { console.log('person改变了',newValue,oldValue); }, { immediate: true }) watch(()=>person.firstName, (newValue, oldValue) => { console.log('person的firstName改变了',newValue,oldValue); }, { immediate: true }) watch([()=>person.firstName,()=>person.lastName], (newValue, oldValue) => { console.log('person的firstName、lastName改变了',newValue,oldValue); }, { immediate: true }) watch([()=>person.job], (newValue, oldValue) => { console.log('person的job改变了',newValue,oldValue); }, { immediate: true, deep: true }),
watchEffect(() => { console.log(JSON.stringify(person)); console.log('watchEffect监视'); }) return { person,fullName,btnEdit,sum,message,btnStuName,btnEditStuHobby,btnEditStuJobA } } } </script> <style> </style>
|