VueVue.js开发技巧Vue

vue起步(5)路由

2017-06-23  本文已影响109人  Mx勇

我们常说的路由是应用于SPA应用,所谓的单页面应用,这是h5新出的一种页面应用模式,就是通过不同的路径(url),达到不同的效果,来使组件之间变化和切换。vue路由,当然需要引用文件vue-router.js,可以通过npm,bower进行下载,官方文档 http://router.vuejs.org/zh-cn/index.html

    <div id="box">
        <div>
            <router-link to="/home">主页</router-link>
            <router-link to="/news">新闻</router-link>
        </div>
        <div>
            <router-view></router-view>
        </div>
    </div>

    <script>
        //组件
        var Home={
            template:'<h3>我是主页</h3>'
        };
        var News={
            template:'<h3>我是新闻</h3>'
        };

        //配置路由
        const routes=[
            {path:'/home', component:Home},
            {path:'/news', component:News},
            {path:'*', redirect:'/home'}
        ];
        //生成路由实例
        const router=new VueRouter({
            routes
        });
        //最后挂到vue上
        new Vue({
            router,
            el:'#box'
        });
    </script>
</body>

路由间的嵌套:

    <div id="box">
        <div>
            <router-link to="/home">主页</router-link>
            <router-link to="/user">用户</router-link>
        </div>
        <div>
            <router-view></router-view>
        </div>
    </div>
    <script type="text/javascript">
    //组件
    var Home={
        template:"<h3>我是主页</h3>"
    }
    var User={  
        template:`
            <div>
                <h3>我是用户信息</h3>
                <ul>
                <li><router-link to="/user/username">某个用户</router-link></li>
                </ul>
                <div>
                    <router-view></router-view>
                </div>
            </div>
        `
    }
    var Username={
        template:'<h3>我是xx用户</h3>'
    }
    //配置路由
    const routes=[
        {path:'/home',component:Home},
        {path:'/user',component:User,
            children:[
                {path:'/user/username',component:Username}
            ]
        },
        {path:'*',redirect:'home'}
    ];
    const router=new VueRouter({
        routes
    }) 
    var vm=new Vue({
        router,
        el:'#box'
    })
    </script>
</body>```
路由里面有两个注意的方法:
router.push({path:'home'});  //直接添加一个路由,表现切换路由,本质往历史记录里面添加一个。
router.replace({path:'news'}) //替换路由,不会往历史记录里面添加。
上一篇 下一篇

猜你喜欢

热点阅读