vueJs+webpack单页面应用--vue-router配置

Posted 觉信

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vueJs+webpack单页面应用--vue-router配置相关的知识,希望对你有一定的参考价值。

vue-route版本要跟vue版本同步,我的vue用的2.0+的,vue-router 也用了最新版2.1+

npm安装vue-router:

$ npm install vue-router --save-dev

使用:

1.引入 vue-router:     import VueRouter from ‘vue-router‘;

2.注册:     Vue.use(VueRouter);

3.配置路径: 

const routes = [
{ path: ‘/goods‘, component: goods },
{ path: ‘/seller‘, component: seller },
{ path: ‘/ratings‘, component: ratings }
];
const router = new VueRouter({
linkActiveClass: ‘active‘,
routes: routes
});

4.初始化Vue(备注:

直接new Vue不赋值 需上面加上 /* eslint-disable no-new */注释

):

/* eslint-disable no-new */
new Vue({
router: router,
...App
}).$mount(‘#app‘);

5.push进来第一个路径

router.push(‘/goods‘);

 

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 VueRouter from ‘vue-router‘;
import goods from ‘./components/goods/goods‘;
import seller from ‘./components/seller/seller‘;
import ratings from ‘./components/ratings/ratings‘;

Vue.use(VueRouter);

const routes = [
  { path: ‘/goods‘, component: goods },
  { path: ‘/seller‘, component: seller },
  { path: ‘/ratings‘, component: ratings }
];

const router = new VueRouter({
  linkActiveClass: ‘active‘,
  routes: routes
});

/* eslint-disable no-new */
new Vue({
  router: router,
  ...App
}).$mount(‘#app‘);

router.push(‘/goods‘);

 

1.  定义路由链接:  <router-link to="/goods">商品</router-link>

2.  路由匹配到的组件将渲染在这里   <router-view></router-view>

App.vue 源码:

<template>
  <div>
    <v-header></v-header>
    <div class="tab">
      <div class="tab-item">
        <router-link to="/goods">商品</router-link>
      </div>
      <div class="tab-item">
        <router-link to="/ratings">评论</router-link>
      </div>
      <div class="tab-item">
        <router-link to="/seller">商家</router-link>
      </div>
    </div>
    <!-- 路由匹配到的组件将渲染在这里 -->
    <router-view></router-view>
  </div>
</template>

<script>
  import header from ./components/header/header;
  export default {
    components: {
      v-header: header
    }
  };
</script>

<style lang="stylus" rel="stylesheet/stylus">
.tab
  font-size: 28px
  display: flex
  .tab-item
    height: 40px
    line-height: 40px
    text-align: center
    flex: 1
</style>

 

以上是关于vueJs+webpack单页面应用--vue-router配置的主要内容,如果未能解决你的问题,请参考以下文章

VueJS + Webpack 代码分割的三种方式

vue 多页面开发(应用)

使用Vuejs编写单js组件

使用 VueJS 全家桶做一个简单的 SPA 应用

webpack 单页面应用实战

webpack 单页面应用实战