vue:vue-router插件引用

版权声明:转载请注明出处 https://blog.csdn.net/fly_distance/article/details/87639757

一、前端路由和vue-router

1、概念(什么是前端路由)
通俗地讲,就是网址,比如 yancyxiao.cn ,再专业一点 , 就是每次 GET.或者 POST 等请求在服务端有一个专门的正则配置列表,然后匹配到具体的一条路径后,分发到不同的 Controller, 进行各种操作,最终将 HTML或数据返回给前端,这就完成了一次 IO。
如果不是很理解,可以参考前端路由

2、vue-router的用法

  • 引入vue-router
    通过npm 安装vue-router,之后通过import导入vue-router
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
  • 配置路由
import ErrorView from '../views/ErrorView'
import TreeMobileView from '../views/TreeMobileView'
export default new Router({
  mode: 'hash',
  base: '/zzb-mobile',
  routes: [
    {
      path: '/error',
      name: 'errorView',
      component: ErrorView
    },
    {
      path: '/tree',
      name: 'treeMobileView',
      component: TreeMobileView
    },
    {
      path: '*',
      name: 'errorView',
      component: ErrorView
    }
  ]
})
  • 挂载到vue实例上
import Vue from 'vue'
import App from './App'
import router from './router'

new Vue({
  el: '#app',
  render: h => h(App),
  template: '<App/>',
  router,
  components: { App }
})
  • 跳转
    方法1:使用<router-link>
<template>
	<div>
		<h1>首页</h1>
		<router-link to="/treeMobileView">跳转到 treeMobileView</router-link>
	</div>
</template>

方法2:类似于window.location.href

<template>
	<div>
		<h1>首页</h1>
		<button @click="handleRouter">跳转到 treeMobileView</button>
	</div>
</template>
<script>
	export default {
		methods: {
			handleRouter () {
				this.$router.push(/treeMobileView/index)
			}
</script>

$router还有其他一些方法 :
• replace
类似于<router-link>的 replace 功能 ,它不会向 history 添加新记录,而是替换掉当前的history 记 录,如 this.$router.push(/treeMobileView/index)
• go
类似于 window.history.go(),在 history 记录中向前或者后退多少步,参数是整数,例如 :
//后退 1 页
this.$router.go(-1) ;
//前进 2 页
this.$router.go(2);

猜你喜欢

转载自blog.csdn.net/fly_distance/article/details/87639757