16-Vue之watch使用

目录

基本使用

示例代码


基本使用

  • $route.path:获取当前路由,页面刷新不会触发

  • created:页面打开和刷新会执行

示例代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>watchs使用</title>
</head>
<body>

    <div id="app">

        <router-link to='/login'>登录</router-link>
        <router-link to='/registered'>注册</router-link>
        <router-view></router-view>
        <h3>{
   
   {mes}}</h3>
    </div>

    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

    <!-- 1.导入路由文件 -->
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>


    <script>
        // 创建组件
        const login={
            template:"<p>登录</p>"

        }
        const registered={
            template:"<p>注册</p>"

        }

        // 路由与组件关联
        const router = new VueRouter({
            routes:[
            {path:'/login',component:login},
            {path:'/registered',component:registered}
            ]
        }
        )


        // 注册组件
        var vm = new Vue({
            el:'#app',
            data:{
                mes:"欢迎!!!"
            },
            methods:{

            },
            // 页面打开和刷新会执行
            created(){
              const path = this.$route.path;
              if(path==="/login"){
                    this.mes = "欢迎进入登录页面"
                }else if (path === "/registered"){
                    this.mes = "欢迎进入注册页面"
                }
              

            },
            router:router,
            // 监听vm实例所有属性变化   $route.path 获取当前路由,页面刷新不会触发
            watch:{
                '$route.path':function(newVal){
                    console.log(newVal)
                    if(newVal==="/login"){
                        this.mes = "欢迎进入登录页面"
                    }else if (newVal === "/registered"){
                        this.mes = "欢迎进入注册页面"
                    }

                }
            }
        })

    </script>
    
</body>
</html>

猜你喜欢

转载自blog.csdn.net/IT_heima/article/details/119852582