学习vue——vue2、vue3 的watch、computed 语法
一、vue3 watch
1 import { ref, watch } from 'vue' 2 3 const user = ref({ name: 'zd', age: 22 }) 4 watch( 5 user, // 监视多个参数:[xx1,xx1] 6 (newValue, oldValue) => { 7 console.log(newValue, oldValue) 8 }, 9 { 10 deep: true, // 监控对象的 11 }, 12 { 13 immediate: true, // 进入页面立即执行 14 }, 15 )
二、vue3 computed
1 import { reactive, computed } from 'vue' 2 const msg = reactive([1, 2, 3, 4, 5]) 3 const jisuan = computed(() => { 4 return msg.filter(item => item > 2) 5 }) 6 </script> 7 8 <template> 9 <p>{{ jisuan }}</p> 10 </template>
三、vue2 watch
简写
1 data() { 2 return { 3 name: "zhangsan", 4 nameTip: "name未改变", 5 }; 6 }, 7 8 watch: { 9 name(newVal, oldVal) { 10 // watch可以监听一些状态发生更改的时候,做一些处理,修改状态,或者异步操作 11 this.nameTip = "name状态改变了"; 12 13 }, 14 },
完整写
1 data :{ 2 return { 3 user:{ 4 name: 'zd', 5 age:15 6 } 7 } 8 } 9 // watch 完整写法 10 watch: { 11 // user 或者 user.name 12 user: { 13 deep: true, 14 immediate: true, 15 handler(newValue){ 16 console.log(newValue) 17 } 18 } 19 }
四、vue2 computed
简写
1 export default { 2 data() { 3 return { 4 firstName: 'John', 5 lastName: 'Doe' 6 }; 7 }, 8 computed: { 9 fullName() { 10 return this.firstName + ' ' + this.lastName; 11 } 12 }