Skip to content

使用步骤 ​

本节目标:理解“使用步骤”的核心思路,并能把它用于实际开发或面试表达。

  • 定义路由,注意每个路由对象的必要属性和额外属性;
  • 创建路由对象,要指定路由模式,路由配置信息;
  • 创建vue实例,use路由;
  • 挂载vue实例;

// 1. 定义路由组件. // 也可以从其他文件导入 const Home = { template: '<div>Home</div>' } const About = { template: '<div>About</div>' } // 2. 定义一些路由 // 每个路由都需要映射到一个组件。 // 我们后面再讨论嵌套路由。 const routes = [ { path: '/', component: Home }, { path: '/about', component: About }, ] // 3. 创建路由实例并传递 routes 配置 // 你可以在这里输入更多的配置,但我们在这里 // 暂时保持简单 const router = VueRouter.createRouter({ // 4. 内部提供了 history 模式的实现。为了简单起见,我们在这里使用 hash 模式。 history: VueRouter.createWebHashHistory(), routes, // routes: routes 的缩写 }) // 5. 创建并挂载根实例 const app = Vue.createApp({}) //确保 use 路由实例使 //整个应用支持路由。 app.use(router) app.mount('#app') // 现在,应用已经启动了! 通过调用 app.use(router),我们会触发第一次导航且可以在任意组件中以 this.$router 的形式访问它,并且以 this.$route 的形式访问当前路由: export default { computed: { username() { // 我们很快就会看到 params 是什么 return this.$route.params.username }, }, methods: { goToDashboard() { if (isAuthenticated) { this.$router.push('/dashboard') } else { this.$router.push('/login') } }, }, }

本站总访问 — 次