头图

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>


image.png

image.png

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>


image.png


锅包肉
97 声望17 粉丝

这个人很懒,没有什么说的。