vue笔记(六)

2024-02-26  本文已影响0人  编程东

vue-router是vue.js官方路由管理器。vue的单页应用是基于路由和组件的,路由用于设定访问路径,并将路径和组件映射起来。这是官方的解释,简单来说就是使前端页面更好地与后端的数据进行交互。

首先,要在开发的vue项目中用到vue-router就要先安装。

npm install vue-router --save

安装好后我们创建一个文件夹router,在文件夹下面创建index.js。


router

然后在index.js下面引入vue-router。

引入
配置 配置
暴露
import VueRouter from "vue-router";
import Vue from "vue";
const home = ()=> import ('@/views/home/Home.vue')

Vue.use(VueRouter)

const routes = [
    {
        path:'',
        redirect:'/home'
    },
    {
        path:'/home',
        name:'home',
        component:home
    }
]

const router = new VueRouter({
    routes,
    mode:'history',
    linkActiveClass:'active'
})

export default router
const home = ()=> import ('@/views/home/Home.vue')

是引入外部的组件或应用。

Vue.use(VueRouter)

将引入的vue-router注册成Vue插件。

const routes = [
    {
        path:'',
        redirect:'/home'
    },
    {
        path:'/home',
        name:'home',
        component:home
    }
]

routes这个数组是必须要有内容的,里面的对象都是每一条路由得相关配置,redirect:'/home'是默认打开的页面是路径为/home的页面。

 mode:'history'

history模式的作用是在去除地址上出现的#符号。

linkActiveClass:'active'

linkActiveClass是给所有的router-link的默认样式该名称,router-link的默认样式名称很长,所以如果要修改的话会有一点麻烦,所以可以给它改成简短一点的名称。

export default router
main.js

最后是要把vue-router暴露出去,因为在使用vue-router的时候需要把它引入,main.js文件中,来对它进行一个全局的使用。

上一篇 下一篇

猜你喜欢

热点阅读