1、HTML和JS中使用router

在HTML中直接使用,如下所示

方法:
1、使用router-link 组件进行导航to 属性指定链接。 router-link 会被默认渲染程一个 < a >标签
2、< router-view > 为路由出口,路由匹配到的组件被渲染在这里

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
   <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

</head>
<body>
<div id = "app">
  <h1>Hello App!</h1>
  <p>
    // 使用router-link 组件进行导航
    // to 属性指定链接
    // router-link 会被默认渲染程一个<a>标签
    <router-link to='/foo'>Go to Foo</router-link>
    <router-link to='/bar'>Go to Bar</router-link>
  </p>
  // 路由出口
  // 路由匹配到的组件被渲染在这里
  <router-view></router-view>
</div>
<script>
</script>
</body>
</html>

JavaScript使用组件进行处理

1、定义路由
2、创建路由实例,传入配置参数
3、创建和挂在跟实例

// 组件,可以是任何形式创建的组件
const foo= {template:`<div>fo</div>`}

//1、定义路由
// path:映射地址
// component:映射的组件
const routes=[
    {path:'/foo',component :foo}
]
// 2、创建路由实例,传入配置参数
const router =new VueRouter({
      routes
})

// 3、创建和挂在跟实例
// 通过router配置参数注入路由
const app =new Vue({
    router
}).$mount("#app")// 挂在到id="app"上

通过注入路由器,我们可以在任何组件内通过 this.$ router 访问路由器,也可以通过 this.$route 访问当前路由:

// Home.vue
export default {
  computed: {
    username() {
      // 我们很快就会看到 `params` 是什么
      return this.$route.params.username
    }
  },
  methods: {
    goBack() {
      window.history.length > 1 ? this.$router.go(-1) : this.$router.push('/')
    }
  }
}
发布了25 篇原创文章 · 获赞 18 · 访问量 986

猜你喜欢

转载自blog.csdn.net/MoonNight608/article/details/104569890