VueRouter-Watch属性

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>67-VueRouter-Watch属性</title>
    <script src="js/vue.js"></script>
    <script src="js/vue-router.js"></script>
</head>
<body>
<!--
1.什么是Watch属性?
Watch属性是专门用于监听数据变化的, 只要数据发生了变化, 就会自动调用对应数据的回调方法

2.Watch监听路由变化
Watch属性不仅仅能够监听数据的变化, 还能够监听路由地址的变化
在企业开发中我们可以通过Watch来判断当前界面是从哪个界面跳转过来的
-->
<!--这里就是MVVM中的View-->
<div id="app">
<!--    <input type="text" v-model="num1" @keyup="change1">-->
    <!--<input type="text" v-model="num1">
    <span>+</span>-->
<!--    <input type="text" v-model="num2" @keyup="change2">-->
    <!--<input type="text" v-model="num2">
    <span>=</span>
    <input type="text" disabled v-model="res">-->
    <a href="#/one">切换到第一个界面</a>
    <a href="#/two">切换到第二个界面</a>
    <router-view></router-view>
</div>
<template id="one">
    <div>
        <p>我是第一个界面</p>
    </div>
</template>
<template id="two">
    <div>
        <p>我是第二个界面</p>
    </div>
</template>

<script>
    // 1.定义组件
    const one = {
        template: "#one",
    };
    const two = {
        template: "#two"
    };
    // 2.定义切换的规则(定义路由规则)
    const routes = [
        // 数组中的每一个对象就是一条规则
        { path: '/one', component: one },
        { path: '/two', component: two }
    ];
    // 3.根据自定义的切换规则创建路由对象
    const router = new VueRouter({
        routes: routes
    });

    // 这里就是MVVM中的View Model
    let vue = new Vue({
        el: '#app',
        // 4.将创建好的路由对象绑定到Vue实例上
        router: router,
        watch: {
            // 可以通过watch监听Model中数据的变化, 只要数据发生变化, 就会自动调用对应的回调函数
          num1: function (newValue, oldValue) {
              // console.log(this.num1);
              // console.log(newValue, oldValue);
              this.res = parseInt(this.num1) + parseInt(this.num2)
          },
          num2: function (newValue, oldValue) {
              this.res = parseInt(this.num1) + parseInt(this.num2)
          },
            // 可以通过watch监听路由地址的变化, 只要路由地址发生变化, 就会自动调用对应的回调函数
          "$route.path": function (newValue, oldValue) {
              console.log(newValue, oldValue);
          }
        },
        // 这里就是MVVM中的Model
        data: {
            num1: 0,
            num2: 0,
            res: 0
        },
        // 专门用于存储监听事件回调函数
        methods: {
            change1(){
                this.res = parseInt(this.num1) + parseInt(this.num2)
            },
            change2(){
                this.res = parseInt(this.num1) + parseInt(this.num2)
            }
        },
        // 专门用于定义计算属性的
        computed: {
        },
        // 专门用于定义局部组件的
        components: {
            one: one,
            two: two
        }
    });
    console.log(vue.$route);
</script>
</body>
</html>