vue中路由参数的使用二

2019-12-03  本文已影响0人  前端Tree

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>

<body>
<div id="app">

<router-link to="/home">首页</router-link>
<router-link to="/news/1">第一条新闻</router-link>
<router-link to="/news/112?a=666">第二条新闻</router-link>
<router-link to="/news/abc">第三条新闻</router-link>

<!-- 路由出口: -->
<router-view></router-view>

</div>

<script src="./vue.js"></script>
<script src="./vue-router.js"></script>
<script>
/*
组件中如何获取 路由参数???
1 在组件模板中获取: route.params.id id 与路由规则中配置的路由参数 :id 保持一致 2 在代码中获取:this.route.params.id
*/

const Home = {
  template: `
    <div>这是 Home 组件</div>
  `
}

const News = {
  template: `
    <div>这是 新闻 组件 --- {{ $route.params.id }} || {{ $route.query.a }}</div>
  `,

  created() {
    console.log('代码中获取路由参数:', this.$route.params.id)
  },

  // 监视路由参数的变化
  // 由 /news/1 直接跳转到 /news/2 就会触发
  watch: {
    $route(to, from) {
      // from 从哪来,上一个路由
      // to   到哪去,当前路由
      // console.log('from:', from)
      // console.log('to:', to)
      console.log('当前路由参数:', to.params.id)
    }
  }
}

// 创建路由实例
const router = new VueRouter({
  // 配置路由规则
  routes: [
    { path: '/home', component: Home },

    // 该路由可以匹配什么样的哈希值???
    // 1 /news/221
    //   /news 是固定写死的, /221 正好被 /:id 匹配

    // 不能匹配:
    // 1 /news  少了 /:id 匹配的不分
    // 2 /abc   从头开始就无法匹配
    // 3 /news/123/adf  多了 /adf 这一部分
    { path: '/news/:id', component: News }
  ]
})

const vm = new Vue({
  el: '#app',
  data: {},
  // 将路由实例挂到Vue实例中
  router
})

</script>
</body>

</html>

上一篇下一篇

猜你喜欢

热点阅读