vue 创建路由
路由
1、安装
cnpm install vue-router -S
2、在创建路由的js中引入
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
3、创建路由
需要创建new 路由实例对象
const router =/export default new VueRouter({
routes:[
{
path:'',
可使用*充当占位符
'/user-*',会匹配以/user-开头的任意路径
this.$route.params.pathMatch,会返回*匹配的内容
name:"", 路由名称,当跳转时指定name属性使用
component: 使用前先引入组件
meta:{键值对} 给路由添加元信息,可通过this/$route.meta.键名获取
}
]
})
4、在主入口组件中(App.vue)使用
<router-view />
5、在main.js中
(1)引入路由文件
import router from './router'
(2)在vue的实例化对象中添加route
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
代码示例:
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'
import App from './App'
import Axios from 'axios'
import VueRouter from 'vue-router'
import HelloWorld from './components/HelloWorld'
Vue.use(VueRouter)
Vue.config.productionTip = false
const router=new VueRouter({
routes:[
{
path:'/hello',
name:"HelloWorld",
component:HelloWorld
}
]
})
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
App.vue:
<template>
<div id="app">
<img src="./assets/logo.png">
<router-view />
</div>
</template>
<script>
export default {
name: 'App',
data()
{
return{
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
还没有评论,来说两句吧...