首先还是先创项目
然后选择vue-router 再创建
再敲代码学习前,我们先了解什么是路由?
路由有一个非常重要的概念就是路由表:
本质就是一个映射表,决定数据的指向。
我们生活中常常听到的路由器,它就是两种机制:路由和转送
·路由是决定数据包从来源到目的地的路径
·转送将输入端的数据转移到合适的输出端
我的理解就是先有个路径然后通过这个路径转送数据√√√√(大佬可以纠正我)
======================================================
项目http://localhost:8080/#/跑起来后
我们就可以了解vue-router url的变化是怎么实现让页面么有刷新的:
有两种方式:
一、通过hash值的变化
location.hash ='' home''
但是url会有个# eg:http://localhost:8080/#/home
二、通过history.pushState
为了没有#就可以用这个
history.pushState({},'','home')
pushState使用最多在于数据结构的栈结构
我的理解:相当于你压入一个地址值,先进后出,后加的就是页面显示的
三、history.replaceState()
就是替换 没法实现网页的前进后退。
四、history.go()
就是go(n)前进n次
负数就是后退n次
history.forward()==history.go(1)
============================================================
现在再component文件中创建两个vue文件一个Home、一个About;
然后为了使这两个组件起作用就在router 文件的route.js文件中配置路由;
import Vue from 'vue'
import Router from 'vue-router'
import Home from '../components/Home.vue'
import About from '../components/About.vue'
//安装router插件 vue.use(插件)
Vue.use(Router)
//创建VueRouter对象
const routes = [
{
path: '/home',
component: Home
},
{
path: '/about',
component: About
}
]
export default new Router({
routes
})
非常的简单!!!!
然后就是让他们显示出来了
在App.vue中写个按钮 和 显示的位置占位router-view
代码如下:
<template>
<div id="app">
<router-link to="/home">首页</router-link>
<router-link to="/about">关于</router-link>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
<style>
</style>
重定向:
{
path: '/',
redirect: '/home'
},
取消url路由的# 在router对象中设置模式 mode:‘history’;
//创建VueRouter对象
const router = new Router({
routes,
mode: 'history'
})
通过代码实现跳转 :
<template>
<div id="app">
<button @click="homeClick">首页</button>
<button @click="aboutClick">关于</button>
<!-- <router-link to="/home" tag="button">首页</router-link>
<router-link to="/about" tag="button" >关于</router-link> -->
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App',
methods: {
homeClick() {
this.$router.push('/home')
},
aboutClick() {
this.$router.push('/about')
}
}
}
</script>
<style>
</style>
今天就到这里吧,有点晚了!!!!!