preface

The lifecycle of Vue3.0 Vue2.0 life cycle
setup beforCreated/created
onBeforeMount beforeMount
onMounted mounted
onbeforeUpdate beforeUpdate
onUpdated updated
onBeforeUnmount beforeDestroy
onUnmounted destoryed

How is it used in Setup

import {onBeforeMount,onMounted,onUpdated,onBeforeUpdate} from 'vue'
export default {
    components:{
        baseButton
    },
    setup(props,context){
        console.log("I am setup")
        onBeforeMount(() = >{
            //do something
        })
        onMounted(() = >{
            //do something
        })
        onUpdated(() = >{
            //do something
        })
        const clickBtn = (data) = >{
            console.log(data)
        }
        return {
            clickBtn
        }
    }
Copy the code

In terms of usage, there is a big difference compared with Vue2.0. Next, we will upgrade Vue3.0 from the input component written using Vue2.0. We can confirm that Vue3.0 is compatible with vue2. x, that is, we can use vue2. x in our daily work The relevant syntax of.

    setup(props,context){
        let boundValue = ref(' ');
        let error = false;
        let haveFocus = false;
        watch(boundValue,(boundValue,newValue) = >{
            console.log(newValue)
        })

        return  {
            boundValue,
            error,
            haveFocus
        }
    }
Copy the code

A watch source can only be A getter/effect function, A ref, A reactive object, or an array of these types.

  • Watch can listen for getters
const state = reactive({ count: 0 })
watch(() = > state.count, (newValue, oldValue) = > {
    // Because watch can only be observed by getter/effect functions, ref, hot active objects, or arrays
    // So you need to change state.count to the getter
})
Copy the code
  • Watch can listen for reactive objects
let boundValue = ref(' ');
watch(boundValue,(newValue,oldValue) = >{
    console.log(newValue)
})

Copy the code
  • Watch can listen to multiple responsive objects, and any one of them updates,
watch([value1,value2],(newValue,oldValue) = >{})Copy the code

If you need to use deep listening and Vue2.0 plus deep: true, the content of this article may be insufficient or have problems, welcome you to put forward your opinion, actively respond to the gold digging activity, this article is participating in the “Gold digging booklet free learning!” Event, click to view details of the event