vue 监听练习

81 阅读1分钟
div id="app">
    h1 @click="stop">{{num}}</h1>
/div>
script src="./vue2.6.14.js"></script>
script>
    new Vue({
        el: "#app",
        data: function () {
            return {
                num: 0,
                timer: null
            }
        },
        created() {
            this.timer = setInterval(() => {
                this.num++
            }, 1000);
        },
        watch: {
            /* num:{
                handler:function(){
                    console.log('余额加1');
                }
            } */
            /* 监听方法的简写方式 */
            num(newV, oldV) {
                console.log(newV, oldV);
                console.log('余额加1,为'+newV);
            }
        },
        methods: {
            stop() {
                /* clearInterval(this.timer) */
                this.$destroy();
            }
        },
        beforeDestroy() {
            /* vue实例化对象还存在 */
            clearInterval(this.timer)
            console.log(this);
        },
        destroyed() {
            console.log(this);
            /* vue实例化对象不存在了 */
        },

    })
</script>