watch监听函数小案例

2021-06-15 11:26:17 浏览数 (2)

代码语言:txt复制
<div id="app">
  <router-link to="/login">登录</router-link>
  <router-link to="/reg">注册</router-link>
  <router-view></router-view>
  <h3>{{msg}}</h3>
</div>
<body>
  <script>
    const login = {
      template: `<h1>登陆组件</h1>`
    }
    const reg = {
      template: `<h1>注册组件</h1>`
    }
    const router = new VueRouter({
      routes:[
        {path:'/login',component:login},
        {path:'/reg',component:reg}
      ]
    });
    let vm = new Vue({
      el: "#app",
      data() {
        return {
          msg:'欢迎登录'
        }
      },
      router,
      watch:{
        '$route.path':function(newval){
          if(newval==='/login'){
            this.msg='欢迎登录'
          }else if(newval==='/reg'){
            this.msg='欢迎注册'
          }
        }
      }
    })
  </script>
</body>

0 人点赞