精华内容
参与话题
问答
  • 基本用法 <!DOCTYPE html> <... <head>...meta charset="UTF-8">... /* .router-link-active{ font-size:20px; color:#ff7300; text-decoration:none; } */ .active{ font

    基本用法

    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<title>路由基本用法</title>
    	<style>
    		/* .router-link-active{
    			font-size:20px;
    			color:#ff7300;
    			text-decoration:none;
    		} */
    		.active{
    			font-size:20px;
    			color:#ff7300;
    			text-decoration:none;
    		}
    	</style>
    	<script src="js/vue.js"></script>
    	<script src="js/vue-router.js"></script>
    </head>
    <body>
    	<div id="itapp">
            <div>
                <!-- a标签 -->
                <router-link to='/home' >主页</router-link>  
                <router-link to='/news'>新闻</router-link> 
            </div>
            <div>
                <!-- 用来显示内容 -->
                <router-view></router-view>
            </div>
    	</div>
    
    	<script>
            // 1.定义组件
            var Home={
    			template:'<h3>我是主页</h3>'
    		}
    		var News={
    			template:'<h3>我是新闻</h3>'
    		}
    		
            // 2.配置路由
            var routesAll= [{
                path:'/home',
                component:Home
            },{
                path:'/news',
                component:News
            }];
            //3. 创建路由实例
    
            var router = new VueRouter({
                routes:routesAll,
                mode:'hash', //history
                linkActiveClass:'active' //当前所处的链接的class
            })
    
            // 4.将router挂载在vue实例上
    		new Vue({
    			el:'#itapp',
                // router:router , 
                router  //注入路由
    		});
    	</script>
    </body>
    </html>
    
    

    路由嵌套传递参数和路由守卫

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
    	<meta charset="UTF-8">
    	<title>路由嵌套和参数传递 tag</title>
    	<style>
    		.active {
    			font-size: 20px;
    			color: #ff7300;
    			text-decoration: none;
    		}
    	</style>
    	<script src="js/vue.js"></script>
    	<script src="js/vue-router.js"></script>
    </head>
    
    <body>
    	<div id="itapp">
    		<div style="position: fixed;top:180px">
    			<router-link to="/home">主页</router-link>
    			<router-link to="/user">用户</router-link>
    		</div>
    		<div style="height:2000px">
    			<router-view></router-view>
    		</div>
    
    		<hr>
    		<button @click="push">添加路由</button>
    		<button @click="replace">替换路由</button>
    	</div>
    
    	<template id="user">
    		<div style="height:2000px">
    			<h2>用户信息</h2>
    			<ul>
    				<router-link to='/user/login?name=tom&pwd=123'>用户登录</router-link>
    				<router-link to='/user/regist/alice/456'>用户注册</router-link>
    			</ul>
    			<router-view></router-view>
    		</div>
    	</template>
    
    	<script>
    		var Home = {
    			template: '<div><h3>我是主页 {{$route.params}}</h3></div>'
    		}
    		var User = {
    			template: '#user'
    		}
    		var Login = {
    			template: '<h4>用户登陆。。。获取参数:{{$route.query}},{{$route.path}}</h4>'
    		}
    		var Regist = {
    			template: '<h4>用户注册。。。获取参数:{{$route.params}},{{$route.path}}</h4>'
    		}
    
    		const routes = [{
    				path: '/home',
    				name: 'home',
    				component: Home
    			},
    			{
    				path: '/user',
    				name: 'user',
    				component: User,
    				beforeEnter(from, to, next) {
    					console.log(`from ${from.fullPath},to ${to.fullPath}`);
    					setTimeout(() => {
    						next();
    					}, 500)
    				},
    				// beforeLeave(from,to,next){
    				//     console.log(`from ${from.fullPath},to ${to.fullPath}`);
    				//     console.log('beforeLeave');
    				//     next();
    				// },
    				//子路由使用: 需要在上一级 (User)路由页面加上router-view
    				// 子路由使用,需要再上一级路由页面加上 router-view 显示。
    				// 使用children属性实现路由嵌套,子路由path前不要加/,否则永远以根路径开始请求
    				children: [{
    					path: 'login',
    					name: 'login',
    					component: Login
    				}, {
    					path: 'regist/:username/:password',
    					name: 'regist',
    					component: Regist
    				}]
    
    			},
    			{
    				path: '*',
    				redirect: '/home'
    			}
    		]
    
    		const routerAll = new VueRouter({
    			routes: routes, //简写,相当于routes:routes
    			linkActiveClass: 'active', //更新活动链接的class类名,默认的激活的 class
    			linkExactActiveClass: 'active-extact', //精确激活的 class
    			mode: "hash", //默认
    			//   页面跳转后,页面是否滚动
    			scrollBehavior(to, from, savedPostion) {
    				if (savedPostion) {
    					return savedPostion;
    				} else {
    					return {
    						x: 0,
    						y: 0
    					}; //每次切换页面都是滚动到页面顶部
    				}
    			}
    		});
    
    		var vm = new Vue({
    			el: '#itapp',
    			router: routerAll, //注入路由
    			// test:routerAll,  //一般不这么写
    			methods: {
    				push() {
    					// 1.字符串形式
    					// this.$router.push('/home')
    					// //2. 对象
    					// this.$router.push({
    					//     path:'/home'
    					// })
    
    					//  //2. 对象,带查询参数
    					//  this.$router.push({
    					//     path:'/home',
    					//     query:{
    					//         plan:'private'
    					//     }
    					// })
    					// 获取参数$route.query, 相当于get
    
    					// 3.命令路由
    					// this.$options.test({
    					//     name:'home',
    					//     params:{
    					//         userid:'123'
    					//     }
    					// });
    
    					this.$router.push({
    						name: 'home',
    						params: {
    							userid: '123'
    						}
    					})
    					// 获取参数$route.params
    
    				},
    				replace() {
    					routerAll.replace({
    						path: 'user'
    					}); //替换路由,没有历史记录
    				}
    			}
    		});
    	</script>
    </body>
    
    </html>
    
    
    展开全文
  • <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>权限控制- filters</title> <style> .active { font-size: 20px;... display
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
    	<meta charset="UTF-8">
    	<title>权限控制- filters</title>
    	<style>
    		.active {
    			font-size: 20px;
    			color: #ff7300;
    			text-decoration: none;
    
    		}
    
    		.main-menu a {
    			display: inline-block;
    			margin-right: 10px;
    		}
    	</style>
    	<script src="js/vue.js"></script>
    	<script src="js/vue-router.js"></script>
    </head>
    
    <body>
    	<div id="itapp">
    		<div class="main-menu">
    			<!-- <router-link to="/home">主页</router-link>
                <router-link to="/user">用户</router-link>
                <router-link to="/finance">财务信息</router-link> -->
    
    			<!-- 写成动态的 -->
    			<!-- $router.options.routes  可以从计算器属性-->
    			<!-- {{$router.options.routes}} -->
    			<router-link v-for="(item,index) in $router.options.routes" :key="index" :to="item.path">{{item.meta.title}}
    			</router-link>
    			<!-- <router-link v-for="(item,index) in getMyRoutes" :key="index" :to="item.path">{{item.meta.title}}</router-link> -->
    
    		</div>
    		<div>
    			<transition enter-active-class="animated bounceInLeft" leave-active-class="animated bounceOutRight">
    				<router-view></router-view>
    			</transition>
    		</div>
    
    		<hr>
    		<button @click="push">添加路由</button>
    		<button @click="replace">替换路由</button>
    	</div>
    
    	<template id="user">
    		<div>
    			<h3>用户信息</h3>
    			<ul>
    				<router-link to="/user/login?name=tom&pwd=123" tag="li">用户登陆</router-link>
    				<router-link to="/user/regist/alice/456" tag="li">用户注册</router-link>
    				<router-link to="/user/info" tag="li">用户注册</router-link>
    			</ul>
    			<router-view></router-view>
    		</div>
    	</template>
    
    	<script>
    		var Home = {
    			template: '<h3>我是主页</h3>'
    		}
    		var User = {
    			template: '#user'
    		}
    		var Login = {
    			template: '<h4>用户登陆。。。获取参数:{{$route.query}},{{$route.path}}</h4>'
    		}
    		var Regist = {
    			template: '<h4>用户注册。。。获取参数:{{$route.params}},{{$route.path}}</h4>'
    		}
    		var Finance = {
    			template: '<h4>财务信息</h4>'
    		}
    
    		var routes = [{
    				path: '/home',
    				component: Home,
    				meta: {
    					title: '首页',
    					roles: ['admin', 'guest']
    				}
    			},
    			{
    				path: '/user',
    				component: User,
    				meta: {
    					title: '用户',
    					roles: ['admin', 'guest']
    				},
    				children: [{
    						path: 'login',
    						component: Login
    					},
    					{
    						//动态路由匹配  // 动态路径参数 以冒号开头
    						path: 'regist/:username/:password',
    						component: Regist
    					}
    
    				]
    			},
    			{
    				path: '/finance',
    				component: Finance,
    				meta: {
    					title: '财务信息',
    					roles: ['admin']
    				}
    			},
    			{
    				path: '*',
    				redirect: '/home',
    				hidden: true
    			}
    		]
    
    		//过滤需要显示的路由 , 权限控制
    		//第一种方式, 通过设置 是否有权限 roles参数来过滤 guest为游客 
    		//假设登录成功, 你知道用户的角色,权限
    		routes = routes.filter((option, index) => {
    			return !option.hidden && (option.meta && option.meta.roles.includes('guest'));
    		})
    
    		const routerAll = new VueRouter({
    			routes, //简写,相当于routes:routes
    			linkActiveClass: 'active', //更新活动链接的class类名,默认的激活的 class
    			linkExactActiveClass: 'active-extact', //精确激活的 class
    			mode: "hash", //默认
    		});
    
    		new Vue({
    			el: '#itapp',
    			router: routerAll, //注入路由
    			// test:routerAll,   //this.$options.test
    			computed: {
    				getMyRoutes() {
    					var thisData = this.$router.options.routes;
    					var test1 = thisData.filter((option) => {
    						return option.meta
    					})
    					return test1;
    				}
    			},
    			methods: {
    				push() {
    					// this.$options.test.push({path:'home'})
    					this.$router.push({
    						path: 'home'
    					}); //添加路由,切换路由
    					// routerAll.push({path:'home'}); //添加路由,切换路由
    
    					// 获取参数 
    					// this.$route.query
    
    				},
    				replace() {
    					routerAll.replace({
    						path: 'user'
    					}); //替换路由,没有历史记录
    				}
    			}
    		});
    	</script>
    </body>
    
    </html>
    
    
    展开全文
  • // import VueRouter from 'vue-router' import VueRouter from '../MYRouter/index.js' Vue.use(VueRouter)// 执行install方法 const routes = [ { path:'/', redirect:'/goods' }, { path: '/goods', ...
    import Vue from 'vue'
    // import VueRouter from 'vue-router'
    import VueRouter from '../MYRouter/index.js'
    
    Vue.use(VueRouter)// 执行install方法
    
    const routes = [
      {
        path:'/',
        redirect:'/goods'
      },
      {
        path: '/goods',
        name: 'goods',
        component: () => import('../views/goods.vue')
      },
      {
        path: '/ratings',
        name: 'ratings',
        component: () => import('../views/ratings.vue')
      },
      {
        path: '/seller',
        name: 'seller',
        component: () => import('../views/seller.vue')
      },
    ]
    //new执行构造函数
    const router = new VueRouter({
      routes,
      linkActiveClass:'active'
    })
    
    export default router
    
    

    自定义插件MYRouter的内部写法

    //我们写插件的地方
    
    let Vue ;
    
    class MYRouter {
        static install(_Vue) {//use执行的函数
            Vue = _Vue;
            Vue.mixin({
                beforeCreate(){
                    // const options = this.$options;
                    //this -- vue实例化对象
                    Vue.prototype.$rmrouter = '我是路由!'
                    if(this.$options.router){
                        //this.$options.router 在vue实例化的时候被注入的router对象
                        this._router = this.$options.router
                        Vue.util.defineReactive(this._router, 'current', '/') ; //方式二
                        //这个是把_route加入数据监控,所以你可以watch到_route
                        this.$options.router.init();
                    }
                    
                }
            })
        }
        constructor(options){
            this.$options = options;
            this.routerMap = {}; 
            
            // this.currentPath = ''; //当前的path
            // 路由  -- 组件
            // test1  --- test1.vue
            // //方式一: 
            // this.app = new Vue({
            //     data(){
            //         return {
            //             //当前的路由
            //             current:'/'
            //         }
            //     }
            // });
       
           
        }
        init(){
            console.log('ppp');
            //1. 监听hash的变化
                this.initEvents();
            //2. 处理路由routerMap
                this.createRouterMap();
            //3 . 初始化组件  , router-link, router-view
                this.initComponent();
            //4.路由守卫
        }
         //1. 监听hash的变化
        initEvents(){
            window.addEventListener('hashchange',this.onHashChange.bind(this),false)
            window.addEventListener('load',this.onHashChange.bind(this),false)
        }
        //2. 处理路由routerMap
        createRouterMap(){
            // this.routerMap = {
            //     '/goods':'component',
            //     '/goods1':'component1',
            // }
            this.$options.routes.forEach((item)=>{
                this.routerMap[item.path] = item;
            })
        }
    
        onHashChange(e){
            console.log('我监听到路由变化了');
            //获取hash
            let hash = location.hash.slice(1) || '/';
            this.current = hash; //方式一
        }
        //3 . 初始化组件  , router-link, router-view
        initComponent(){
            Vue.component('router-link',{
                // props:['to'],
                props:{
                    to:String
                },
                render:function(h){
                    // h-- createElemnt
                    //  3个参数
                    //  dom节点名
                    //  属性
                    //  子元素
                    return h('a',{
                        attrs:{
                            href:'#'+this.to
                        }
                    },[this.$slots.default])
                }
            });
    
            Vue.component('router-view',{
                render:h=>{
                    console.log('ppp');
                    // console.log(this.app.current); //方式一
                    //this vuerouter实例化构造函数的对象
                    
                    let component = this.routerMap[this.current].component;
                    return h(component);
                }
            })
    
        }
    
    }
    export default MYRouter;
    
    
    展开全文
  • import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App...import {HashRouter,BrowserRouter} from 'react-router-dom' ReactDOM.render( <BrowserRouter&
    import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.css';
    import App from './App';
    import * as serviceWorker from './serviceWorker';
    import {HashRouter,BrowserRouter} from 'react-router-dom'
    
    ReactDOM.render(
        <BrowserRouter>
            <App/>
        </BrowserRouter>
    , document.getElementById('root'));
    
    // If you want your app to work offline and load faster, you can change
    // unregister() to register() below. Note this comes with some pitfalls.
    // Learn more about service workers: https://bit.ly/CRA-PWA
    serviceWorker.unregister();
    
    
    import React from 'react'
    import {NavLink,Link,Route,Redirect,Switch} from 'react-router-dom'
    import About from './views/about'
    import Home from './views/home'
    class App extends React.Component {
      render () {
        return (
          <div>
            <div className="row">
              <div className="col-xs-offset-2 col-xs-8">
                <div className="page-header">
                  <h2>React 路由案例</h2>
                </div>
              </div>
            </div>
    
            <div className="row">
              <div className="col-xs-2 col-xs-offset-2">
                <div className="list-group">
                  {/*导航路由链接*/}
                  <NavLink to="/about" className="list-group-item">About</NavLink>
                  <NavLink to="/home" className="list-group-item">Home</NavLink>
                </div>
              </div>
              <div className="col-xs-6">
                <div className="panel">
                  <div className="panel-body">
                    <Switch>{/*只匹配一次*/}
                      <Route path="/about" component={About}></Route>
                      <Route path="/home" component={Home}></Route>
                      <Redirect to="/home"></Redirect>
                    </Switch>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )
      }
    }
    
    export default App
    
    
    import React from 'react'
    import {NavLink,Link,Route,Redirect,Switch} from 'react-router-dom'
    import News from './news'
    import Message from './message'
    export default function Home() {
      return (
        <div>
          <h2>Home组件内容</h2>
          <div>
            <ul className="nav nav-tabs">
              <li>
                <NavLink to="/home/news">
                News
                </NavLink>
                
              </li>
              <li>
                <NavLink to="/home/message">
                message
                </NavLink>
              </li>
            </ul>
            <Switch>
              <Route path="/home/news" component={News}></Route>
              <Route path="/home/message" component={Message}></Route>
              <Redirect to="/home/news"></Redirect>
            </Switch>
          </div>
        </div>
      )
    }
    
    
    import React from 'react'
    export default function About() {
      return (
        <div>
          <h2>About组件内容</h2>
          <div>
            about组件
          </div>
        </div>
      )
    }
    
    
    import React from 'react'
    class News extends React.Component {
        state = {
            newsArr:['news001','news002','news003']
        }
      render () {
          const {newsArr} = this.state
        return (
            newsArr &&newsArr.map((item,index)=><li key={index}>{item}</li>)
        )
      }
    }
    
    export default News
    
    
    import React from 'react'
    import {NavLink,Link,Route,Redirect,Switch} from 'react-router-dom'
    import MessageDetail from './messageDetail'
    class Message extends React.Component {
        state = {
            messages:[]
        }
        componentDidMount(){
            setTimeout(()=>{
                const messages = [
                    {id:1,title:'m1'},
                    {id:2,title:'m2'},
                    {id:3,title:'m3'},
                ]
                this.setState({
                    messages
                })
            },1000)
        }
        render () {
            const {messages} = this.state
            const show = messages.length ? 'none' : 'block'
            return (
                <div>
                    <p style={{display:show}}>loading.......</p>
                    <ul>
                        {
                            messages && messages.map((item,index)=>{
                                return (
                                    <li key={index}>
                                        <Link to={`/home/message/${item.id}`}>{item.title}</Link>
                                    </li>
                                )
                            })
                        }
                    </ul>
                    <Route path="/home/message/:id" component={MessageDetail}></Route>
                </div>
            )
        }
    }
    
    export default Message
    
    
    import React from 'react'
    const messageDetails = [
        {id:1,title:'详细信息1',content:'我爱你祖国'},
        {id:2,title:'详细信息2',content:'我爱你父母'},
        {id:3,title:'详细信息3',content:'我爱你老婆'},
    ]
    export default function MessageDetail(props) {
        const id = props.match.params.id//匹配路由参数
        const md = messageDetails.find(md=>md.id == id)
        console.log(md);
        
        // 拿到二级路由穿过来的id值 进行匹配
      return (
        <div>
          <ul>
            <li>id:{md.id}</li>
            <li>title:{md.title}</li>
            <li>content:{md.content}</li>
          </ul>
        </div>
      )
    }
    
    
    展开全文
  • 一、 addRoutes权限控制 场景: 对登陆成功后的用户可能会有不同的身份权限, 看到的系统菜单以及功能不一样, 这个时候需要用到 动态路由的方式来处理 ...import VueRouter from "vue-router"; Vue.use(VueRout
  • var router = express.Router(); //可挂载路由处理程序 // 路由器的中间件 router.use(function timeLog (req, res, next) { console.log('Time: ', Date.now()) next() }) // 首页路由 router.get('/home', ...
  • vue-router学习地址

    万次阅读 2020-03-24 19:25:47
    vue教程
  • html中使用vue-router

    万次阅读 2020-07-07 00:43:01
    引入vue和vue-router <script src="https://unpkg.com/vue/dist/vue.js"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> 完整的示例 <!DOCTYPE ...
  • vue之router-view组件的使用

    万次阅读 多人点赞 2018-04-26 19:01:08
    开发的时候有时候会遇到一种情况,比如 :点击这个链接跳转到其他组件的情况,通常会跳转到新的页面,蛋是,我们不想跳转到新页面,只在当前页面切换着显示,那么就要涉及到路由的嵌套了,也可以说是子路由的使用。...
  • 最近在研究react,遇到一个编程路由跳转问题,其实我就是想实现,如果像vue-router的方式通过this.$router.push({name: '', ''});类似的方式实现跳转到不同的组件,网上找了好多方法,都不行,不知道错在哪里,求...
  • 安装了vue-router后,router-link连带标签都消失了,有使用elementui ![图片说明](https://img-ask.csdn.net/upload/201912/17/1576565918_952396.png) ![图片说明]...
  • vue router返回到指定的路由

    万次阅读 2020-10-30 10:11:45
    项目场景: 项目场景:示例:A(商品详情)——B(商品购买页面)-C(支付成功页面)——D(订单页面) 问题描述: 提示:这里描述项目中遇到的问题: 如果我们不做控制的话,安卓按照浏览器返回机制,依次从D-C-B-A这...
  • 我想要的是一个<router-link>只对应一个<router-view>标签(也就是点击某个<router-link>只会在对应的<router-view>中渲染) 放一张失败的图片: ![图片说明]...
  • vue-router(路由)详细教程

    万次阅读 多人点赞 2018-05-28 21:08:30
      由于Vue在开发时对路由支持的不足,于是官方补充了vue-router插件。vue的单页面应用是基于路由和组件的,路由用于设定访问路径,并将路径和组件映射起来。传统的页面应用,是用一些超链接来实现页面切换和跳转的...
  • 根据vue-router实现简易版router路由

    千次阅读 2018-10-28 23:30:35
    前些天看了下vue-router的源码结构,理解了下 router-view 和 router-link 的基本实现;所以简单写一个vue-router的小功能版本,实现基本的路由切换,就可以了;好吧,接下来我们开始吧 ~~ 一、最终路由切换展示 ...
  • vue-router传递参数的几种方式

    万次阅读 多人点赞 2018-07-06 16:24:29
    vue-router传递参数分为两大类编程式的导航 router.push声明式的导航 &lt;router-link&gt;编程式的导航 router.push编程式导航传递参数有两种类型:字符串、对象。字符串字符串的方式是直接将路由地址以字符...
  • m-Router 3.1

    千次下载 热门讨论 2010-09-18 14:13:31
    不用说,手机通过蓝牙上网电脑端软件。没有wifi同样免费上网 问题咨询:zhanmail@foxmail.com

空空如也

1 2 3 4 5 ... 20
收藏数 76,423
精华内容 30,569
关键字:

router