1、HTML和JS中使用router

目录

  • 介绍
  • 在HTML中直接使用
  • JavaScript使用组件进行处理

介绍

学习vue-router的一些学习笔记,所有笔记内容请看 vue-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 会被默认渲染程一个标签
    <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:`
fo
`
} //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('/')
    }
  }
}

你可能感兴趣的:(vue-router)