16、Vue 路由

2019-03-07  本文已影响0人  msqt

步骤:

1、安装
npm install vue-router --save

2、引入并实例化(main.js中)
import VueRouter from 'vue-router'

Vue.use(VueRouter);//官方插件都这样用


image.png

3、引入、创建组件(main.js中)
import Home from './components/Home.vue';
import News from './components/News.vue';


image.png

4、配置路由(main.js中)
const routes=[
{path:'/home',component:Home},
{path:'/news',component:News},
{path:'*',component:Home},//默认跳转路由
]


image.png

5、//5、实例化VueRouter:(main.js中)
const router = new VueRouter({
routes//(或写成routes:routes)
})

image.png

6、挂载router(main.js中)


image.png

new Vue({
el: '#app',
//6、挂载router
router,
components: { App },
template: '<App/>'
})
7、将路由出口:(App.vue中)
<router-link to="/home">首页</router-link>
<router-link to="/news">新闻</router-link>
<router-view></router-view>放在App.vue中

image.png

main.js:
// The Vue build version to load with the import command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'//引入vue实例
import App from './App'
//1、引入VueRouter
import VueRouter from 'vue-router'

import VueResource from 'Vue-resource'
//从'Vue-resource'中引入模块,并命名为'VueResource'
Vue.config.productionTip = false;
Vue.use(VueResource);//官方插件都这样用
//2、Vue.use(VueRouter);
Vue.use(VueRouter);

//3、创建组件
import Home from './components/Home.vue';
import News from './components/News.vue';

//4、配置路由
const routes=[
{path:'/home',component:Home},
{path:'/news',component:News},
{path:'*',component:Home},//默认跳转路由
]
//5、实例化VueRouter:
const router = new VueRouter({
routes//(或写成routes:routes)
})
new Vue({
el: '#app',
//6、挂载router
router,
components: { App },
template: '<App/>'
})

//7、将路由出口:<router-view></router-view>放在App.vue中

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',
data (){
return{
msg:'你好!',
}
},
methods:{

},

}
</script>

<style>

app {

font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #2c3e50;
margin-top: 60px;
}
</style>

上一篇下一篇

猜你喜欢

热点阅读