路由可以让其他组件挂在到根组件上。

vue路由配置:

1.安装

cnpm install vue-router  --save

2.在main.js引入并实例化

import VueRouter from 'vue-router'
Vue.use(VueRouter)

3.创建组件并在main.js 配置路由

  • 引入组件
import Home from './components/Home.vue';
import News from './components/News.vue';
  • 定义路由
const routes = [
  { path: '/home', component: Home },
  { path: '/news', component: News },
  { path: '*', redirect: '/home' }   /*默认跳转路由*/
];
  • 实例化VueRouter
const router = new VueRouter({
  routes // (缩写)相当于 routes: routes
})
  • 挂载
new Vue({
    el: '#app',
    router,
    render: h => h(App)
})

4.根组件的模板里面放上这句话

<router-view></router-view>  

5.根组件的模板路由跳转

<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>

示例:

创建Home组件、News组件。
在main.js中配置
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router';

Vue.use(VueRouter);

Vue.config.productionTip = false;

import Home from "./components/Home";
import News from "./components/News";

const routes = [
    {path: "/home", component: Home},
    {path: "/news", component: News},
    {path: "*", redirect: "/home"},
];
const router = new VueRouter({
    routes//是routes:routes 的简写
});


new Vue({
    router,
    render: h => h(App),
}).$mount('#app');
App.vue
<template>
    <div id="app">
        <router-link to="/home">首页</router-link>
        <router-link to="/news">新闻</router-link>
        <router-view></router-view>
    </div>
</template>

<script>
    export default {
        name: 'App',
        components: {},
        data() {
            return {}
        }
    }
</script>

动态路由与 get 传值

1.动态路由

this.$route.params /获取动态路由传值/

News.vue
<template>
    <div id="news">
        <p>新闻页</p>
        <ul>
            <li v-for="(item,key)  in list" :key="item">
                <router-link :to="'/news-content/'+key">{{key}}---{{item}}</router-link>
            </li>
        </ul>
    </div>
</template>

<script>
    export default {
        name: "News",
        data() {
            return {
                msg: "这是新闻组件",
                list: ["新闻1", "新闻2", "新闻3"],
            }
        }
    }
</script>
NewsContent.vue
<template>
    <div id="newContent">
        <p>这是新闻内容</p>
        <p>id 为:{{newsId}}</p>
    </div>
</template>

<script>
    export default {
        name: "NewsContent",
        data() {
            return {
                newsId: ""
            }
        },
        methods: {},
        mounted() {
            this.newsId = this.$route.params.newsId;
        },
    }
</script>
main.js
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router';

Vue.use(VueRouter);

Vue.config.productionTip = false;

import News from "./components/News";
import NewsContent from "./components/NewsContent";

const routes = [
    {path: "/news", component: News},
    {path: "/news-content/:newsId", component: NewsContent},
    {path: "*", redirect: "/home"},
];
const router = new VueRouter({
    routes
});


new Vue({
    router,
    render: h => h(App),
}).$mount('#app');

2. get传值

this.$route.query //获取get传值
示例:

Home.vue
<template>
    <div id="home">
        <p>首页</p>
        <ul>
            <li v-for="(item,key) in list" :key="item">
                <router-link :to="'/home-content?homeId='+key">{{item}}</router-link>
            </li>
        </ul>
    </div>
</template>

<script>
    export default {
        name: "Home",
        data() {
            return {
                msg: "这是首页",
                list: ["首页1", "首页2", "首页3"]
            }
        }
    }
</script>
HomeContent.vue
<template>
    <div id="homeContent">
        <p>首页内容id为:{{homeId}}</p>
    </div>
</template>

<script>
    export default {
        name: "HomeContent",
        data() {
            return {
                homeId: ""
            }
        },
        mounted() {
            this.homeId = this.$route.query.homeId;
        }
    }
</script>
main.js
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router';

Vue.use(VueRouter);

Vue.config.productionTip = false;

import Home from "./components/Home";
import HomeContent from "./components/HomeContent";

const routes = [
    {path: "/home", component: Home},
    {path: "/home-content", component: HomeContent},
    {path: "*", redirect: "/home"},
];
const router = new VueRouter({
    routes
});


new Vue({
    router,
    render: h => h(App),
}).$mount('#app');

示例:vuedemo路由结合请求数据

News.vue
<template>
    <div id="news">
        <p>新闻页</p>
        <ul class="newList">
            <li v-for="(item,key)  in list" :key="key">
                <router-link :to="'/news-content/'+item.aid">{{item.title}}</router-link>
            </li>
        </ul>
    </div>
</template>

<script>
    export default {
        name: "News",
        data() {
            return {
                msg: "这是新闻组件",
                list: [],
            }
        },
        methods: {
            getNewsList() {
                let api = 'http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1';
                this.$http.get(api).then((res) => {
                    this.list = res.body.result;
                })
            }
        },
        mounted() {
            this.getNewsList();
        }
    }
</script>

<style scoped>
    .newList li {
        height: 3.4rem;
        line-height: 3.4rem;
        font-size: 1.5rem;
    }
    .newList li a{
        color: #2c3e50;
    }
</style>
NewsContent.vue
<template>
    <div id="newContent">
        <h2>{{list.title}}</h2>
        <div v-html="list.content"></div>
    </div>
</template>

<script>
    export default {
        name: "NewsContent",
        data() {
            return {
                newsId: "",
                list: []
            }
        },
        methods: {
            getNewsContent: function (newsId) {
                let api = 'http://www.phonegap100.com/appapi.php?a=getPortalArticle&aid=' + newsId;
                this.$http.get(api).then((res) => {
                    this.list = res.body.result[0];
                })
            }
        },
        mounted() {
            this.newsId = this.$route.params.newsId;
            this.getNewsContent(this.newsId);
        },
    }
</script>

<style scoped>

</style>

Vue路由编程式导航以及hash模式

编程式导航:

通过JavaScript来实现路由跳转。有两种方式可以实现。

例子:想通过首页按钮跳转到新闻页
Home.vue
<template>
    <div id="home">
        <p>首页</p>
        <button @click="linkNews">点击跳转新闻页</button>
    </div>
</template>

<script>
    export default {
        name: "Home",
        data() {
            return {
                msg: "这是首页",
            }
        },
        methods: {
            linkNews: function () {
                //方法一:{path: "/news", component: News}
                this.$router.push({path: 'news'});//推荐
                //方法二:需要在main.js中routes里改为{path: "/news", component: News,name:"newsShow"},
                //this.$router.push({name:'newsShow'});
            }
        }
    }
</script>

hash模式:

像这种http://localhost:8080/#/news,路由中含有#。要想改为history模式(即不含#)在main.js中 增加:mode: 'history'。但history可能会出问题,需要配合后台进行设置。

const router = new VueRouter({
  mode: 'history',   /*hash模式改为history*/
  routes // (缩写)相当于 routes: routes
})

路由的嵌套

举例:
--首页
--新闻
--用户(User.vue)
-----用户列表(UserList.vue)
-----增加用户(UserAdd.vue)
1.配置路由(main.js中)

{
    path: '/user',
    component: User,
    children:[
        { path: 'useradd', component: UserAdd },
        { path: 'userlist', component: Userlist }
    ]
}

2.父路由里面配置子路由显示的地方

<router-view></router-view>
User.vue
<template>
    <div id="user">
        <div class="userLift">
            <ul>
                <li><router-link to="/user/userList">用户列表</router-link></li>
                <li><router-link to="/user/userAdd">增加用户</router-link></li>
            </ul>
        </div>
        <div class="userRight">
            <router-view></router-view>
        </div>
    </div>
</template>

<script>
    export default {
        name: "User"
    }
</script>

<style scoped>
    #user{
        padding-left: 5px;
        display: flex;
    }
    .userLift {
        width: 200px;
        min-height:400px;
    }
    .userLift li{
        height: 40px;
        line-height: 40px;
        border-right: 2px solid #2c3e50;
    }
    .userLift li a{
        color: aquamarine;
    }
    .userRight {
        flex: 1;
    }
</style>
UserList.vue
<template>
    <div id="userList">
        这是用户列表
    </div>
</template>

<script>
    export default {
        name: "UserList"
    }
</script>

<style scoped>

</style>
UserAdd.vue
<template>
    <div id="userAdd">
        这是增加用户
    </div>
</template>

<script>
    export default {
        name: "UserAdd"
    }
</script>

<style scoped>
</style>
mian.js 注意子路由path不能加”/“
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router';
import VueResource from "vue-resource";

Vue.use(VueRouter);
Vue.use(VueResource);
import './assets/css/basic.scss';

Vue.config.productionTip = false;

import Home from "./components/Home";
import News from "./components/News";
import User from "./components/User";
import NewsContent from "./components/NewsContent";
import HomeContent from "./components/HomeContent";
import UserList from "./components/User/UserList";
import UserAdd from "./components/User/UserAdd";

const routes = [
    {path: "/home", component: Home},
    {path: "/news", component: News,name:"newsShow"},
    {path: "/news-content/:newsId", component: NewsContent},
    {path: "/home-content", component: HomeContent},
    {path:"/user",component:User,children:[
            {path:'userAdd',component:UserAdd},
            {path: 'userList',component: UserList}
        ]},
    {path: "*", redirect: "/home"},
];
const router = new VueRouter({
    routes
});


new Vue({
    router,
    render: h => h(App),
}).$mount('#app');

路由模块化

将路由逻辑从main.js中封装成模块。
router----->>router.js

import Vue from 'vue'
//配置路由
import VueRouter from 'vue-router';

Vue.use(VueRouter);

import Home from "../components/Home";
import News from "../components/News";
import User from "../components/User";
import Picture from "../components/Picture";
import NewsContent from "../components/NewsContent";
import HomeContent from "../components/HomeContent";
import UserList from "../components/User/UserList";
import UserAdd from "../components/User/UserAdd";

const routes = [
    {path: "/home", component: Home},
    {path: "/news", component: News, name: "newsShow"},
    {path: "/picture", component: Picture},
    {path: "/news-content/:newsId", component: NewsContent},
    {path: "/home-content", component: HomeContent},
    {
        path: "/user", component: User, children: [
            {path: 'userAdd', component: UserAdd},
            {path: 'userList', component: UserList}
        ]
    },
    {path: "*", redirect: "/home"},
];
//实例化VueRouter
const router = new VueRouter({
    routes
});
export default router;

在main.js引入模块

import router from './router/router'

梁柱
135 声望12 粉丝

« 上一篇
4.vue组件通信
下一篇 »
7.Vuex