watch 和 watchEffect
<script>
//import Hello from "./components/Hello.vue";
import {ref,reactive,toRefs,watch, watchEffect} from "vue";
export default {data() {
return {message: 'hellokougou'};
},
setup(){//setup 组件被创立之前执行,不须要应用 this
const counter=ref(0)
function changeCounter(){counter.value++}
const user=reactive({
name:'tom',
age:56,
})
function changeName(){user.name='sean'}
watch(counter, (newVal,oldVal)=>{console.log('new',newVal)
console.log(oldVal)
})
watch(user,(newVal,oldVal)=>{console.log('new',newVal)
console.log(oldVal)
})
// 只有一个回调函数
watchEffect(()=>{console.log(user.name,'watcheffect')
})
return {counter,user,changeCounter,changeName}
},
// 选项式 api
watch:{messages:function (newVal,oldVal){console.log(newVal)
}
},
methods:{ },
components:{//Hello}
}
</script>
<template>
<div>
<h2>{{counter}}</h2>
<button @click="changeCounter">changeCounter</button>
<h2>{{user.name}}</h2>
<button @click="changeName">changeName</button>
</div>
</template>
watchEffect 不须要有监听属性的,只有在回调中援用了响应式的属性
watch 只能监听指定的属性,且能够搞多个
computed
<script>
//import Hello from "./components/Hello.vue";
import {ref,reactive,toRefs,watch, watchEffect,computed} from "vue";
export default {data() {
return {message: 'hello6666666666666'};
},
setup(){//setup 组件被创立之前执行,不须要应用 this
const msg=ref('hellokugou')
const reverseMsg=computed(()=>{ // 返回一个带有 value 属性的对象
return msg.value.split('').reverse().join('')
})
console.log(reverseMsg.value,'----reverseMsg.value')
return {msg,reverseMsg}
},
// 选项式 api
computed:{reverseMsg2:function(){return this.message.split('').reverse().join('')
}
},
methods:{ },
components:{//Hello}
}
</script>
<template>
<div>
<h2>{{msg}}</h2>
<h2>{{reverseMsg}}</h2>
</div>
</template>