vue路由router的使用与搭建

vue路由router的使用与搭建

  1. 前端路由

    1. hash值方式#/id不会向服务器发起请求,根据hash值的改变,对应渲染不同的前端组件
    2. history方式无#号
  2. router配置

    import Vue from 'vue'
    VUe.use(ROuter)
    
    
    export default new Router({
        mode:'history'//是否使用history模式不传默认hash
        routes:[
            {
                path:'/home',
                name:"APP",
                components:App
                
            }
        ]
    })
    
  3. 渲染路由组件告诉在哪渲染((命名后可指定使用哪个router-view渲染)

    router-view渲染子页面

    <template>
      <div id="app">
          <div class="wrap">
             //跳到对应的路径path时,router-view就会渲染相应页面(vue单页应用) 
              //简单就是这个页面没有改变,切换路由切换的只是其中嵌套的内容
                <router-view name="header"></router-view>
    			 <router-view name="main"></router-view>
          </div>
      </div>
    </template>
    
    import Header from '../cpmponents/header
    import Home from '../pages/home
    routes:[
           {
               path:'/home',
               name:"Hone",
               components:{
                   header:Header,//在名叫header的区域渲染Header组件
                   main:App
               }
               
           }
       ]
    
  4. 路由访问

    • this.$router访问路由

    • this.$route访问当前路由(可以查看当前路由的所有参数)

      组件复用时可以用wacth来监视修改$route来响应渲染路由
      watch:{
          $route(newValue,oldValue)
      }
      
  5. 路由的跳转

    • 1. 如果to 需要动态绑定 :to ="'/'"中表示的是js表达式,字符串要用' ' 包裹;
    • 编程式跳转 this.$router.push("/")
    • 通过path跳转 push({path:"/",params"{id:1}})
    • 通过name跳转;push({name:“home”,query"{id:1}})name与params互斥
    • this.$router.back() 返回上一页
  6. 嵌套路由

    • 添加children:[

      ​ {

      ​ path:"/",

      ​ component:“path”

      ​ }

      ]

  7. 路由传参

    • path:"/detail/:id"

    • 获取参数的方式:this.$route.params

    • props:传参设置一个熟悉props:true;在路由目的地可以添加

      props[“id”],获取到

       {
          	path: "/detail/:id",
          	component: Detail,
          	meta: {
          		navTitle: "详情"
          	},
      目标文件
      export default {
      		name: "Detail",
      		props: ["id"],
      		created() {
      			console.log(this);
      		},
      		methods: {
      			back() {
      				this.$router.back();
      			},
      			backToHome() {
      				this.$router.push("/home");
      			}
      		}
      	}
      
      
  8. 路由重定向:

    • redirect:"",当访问某一路径,跳转到此路径(访问‘/’自动跳转到/home)

       {
          	path: "/",
          	redirect: "/home",
          	meta: {
          		navTitle: ""
          	}
          }
      

猜你喜欢

转载自blog.csdn.net/marendu/article/details/90665388