Vue CLI + Vue Router项目建立示例

{{ time }}

前提是已经安装好npm和vue

Step1 建立项目

vue create hello-world

Step2 在项目目录,输入如下指令,并打开项目预览

npm run serve

Step3 安装Vue Router

npm  install  vue-router --save

Step4 建立如下文件

/src/components/Home.vue:

<template>
  <h3>我是主页</h3>
</template>

/src/components/News.vue:

<template>
  <h3>我是新闻</h3>
</template>

/src/router.config.js:

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

export default {
  routes: [
    { path: '/home', component: Home },
    { path: '/news', component: News },
    { path: '*', redirect: '/home' }
  ]
}

Step5 调整/src/main.js像下面

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import routerConfig from './router.config.js'
Vue.use(VueRouter)
const router = new VueRouter(routerConfig)

Vue.config.productionTip = false

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

Step6 编辑/src/App.vue为下面

<template>
  <div id="app">
    <!-- 菜单 -->
    <ul>
      <li class="menu">
        <router-link to="/home">主页</router-link>
        <router-link to="/news">新闻</router-link>
      </li>
    </ul>
    <!-- /菜单 -->

    <div>
      <router-view></router-view>
    </div>

  </div>
</template>

<script>
export default {
  name: 'app',
  data() {
    return {
      msg: '啥玩意儿?',
    }
  },
}
</script>

<style scoped>
.menu > * {
  padding: 10px;
}
</style>

然后刷新页面就可以看见路由器啦。

参考文献:
https://www.cnblogs.com/yuyujuan/p/9839705.html