Vue静态路由

作者: 剑有偏锋 | 来源:发表于2018-08-01 18:51 被阅读183次

一 创建测试项目

vue init webpack-simple vuedemo

二 进入demo目录

cd vuedemo

三 安装依赖

cnpm install

四 安装 vue-router

cnpm install vue-router --save

五 修改代码

├── src
│ ├── App.vue
│ ├── components
│ │ ├── Home.vue
│ │ └── News.vue
│ ├── main.js

App.vue

<template>
  <div id="app">
    <router-link to="/home">home</router-link>
    <router-link to="/news">news</router-link>
    <hr>
    <br>
    <router-view></router-view>

  </div>
</template>

<script>

import Home from './components/Home.vue';
import News from './components/News.vue';

export default {
  name: "app",
  data() {
    return {
      msg:'hello vue world!',     
    };
  },
  components:{
    'v-home':Home,
    'v-news':News
  },
};
</script>

<style>

</style>

Home.vue

<template>
    <!-- all content need in root-->
    <div>      
        {{msg}}Home
        <br>
    </div>
</template>


<script>


export default {
    data(){
        return {
            msg:'i am home component!'
        }
    }
}
</script>

<style>
</style>

News.vue

<template>
    <!-- all content need in root-->
    <div>      
        {{msg}}News
         <br>
        
    </div>
</template>


<script>

export default {
    data(){
        return {
            msg:'i am news component!'
        }
    }    
}
</script>

<style>

</style>

main.js

import Vue from 'vue'
import App from './App.vue'

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

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'}
]

const router = new VueRouter({
  routes
})

new Vue({
  el: '#app',
  router,
  render: h => h(App)
})

六 运行

npm run dev


image.png

七 总结

《1 main.js引入组件
import VueRouter from 'vue-router'
Vue.use(VueRouter)

《2 定义路由
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'} //重定位路由,把不在路由表的都定位到/home
]
然后就可以通过http://localhost:8080/#/home http://localhost:8080/#/news访问了

《3 实例化VueRouter
const router = new VueRouter({
routes
})

《4 挂载路由
new Vue({
el:'#app',
router,
render: h=> h(App)
})

5 根组件模板App.vue,增加router模板
<router-view></router-view>

6 生成导航栏App.vue
<router-link to="/home">home</router-link>
<router-link to="/news">news</router-link>

八 参考

https://router.vuejs.org/

相关文章

网友评论

    本文标题:Vue静态路由

    本文链接:https://www.haomeiwen.com/subject/yrhrvftx.html