Vue拾遗 —— vue-router 基本使用

Vue路由项目文件基础结构

在这里插入图片描述

自定义组件(components)

定义两个组件,最后希望实现同一页面中两个组件的自由跳转。

Content.vue

<template>
  <h1>内容页</h1>
</template>

<script>

export default {
  name: 'Content'
}
</script>

<style scoped>

</style>

Main.vue

<template>
  <h1>主页</h1>
</template>

<script>

export default {
  name: 'Main'
}
</script>

<style scoped>

</style>

路由配置文件(router文件夹下的index.js)

文件内容包括:

  1. 引入路由
  2. 引入自定义组件
  3. 配置路由的路径、路由名称(可也不添加)及跳转的组件
import Vue from 'vue'
import VueRouter from 'vue-router' // 1

// 2
import Content from '../components/Content'
import Main from '../components/Main'

Vue.use(VueRouter)

export default new VueRouter({
    // 3
    routes:[
    {
        // 路由的路径
        path:'/content',
        // 路由名称(可以不添加)
        name:'content',
        // 跳转的组件
        component:Content
    },
    {
        // 路由的路径
        path:'/main',
        // 路由名称(可以不添加)
        name:'main',
        // 跳转的组件
        component:Main
    }
]
})

主配置文件下引入路由配置文件

main.js,此文件为项目执行入口

import Vue from 'vue'
import App from './App'

import router from './router' // 引入路由配置文件

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router, //配置路由
  components: { App },
  template: '<App/>'
})

路由的使用

App.vue
其中router-link为路由链接标签,router-view为跳转组件显示标签。

<template>
  <div id="app">
    <h1>vue-router 使用</h1>
    <router-link to="/main">首页</router-link>
    <router-link to="/content">内容页</router-link>
    <router-view></router-view>
  </div>
</template>

<script>

export default {
  name: 'App'
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

效果

点击首页:
在这里插入图片描述
点击内容页:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/xiecheng1995/article/details/106169689