一篇搞定vue-router

  由于Vue常见于前后端分离开发场景下,所以页面跳转工作全部交给了前端,所以基于集中管理的原则,就有了vue-router插件,它给定了url和组件之间的跳转规则

 

Demo准备

  • vue init webpack-simple vue-router
  • cd vue-router
  • npm install
  • npm install vue-router -S

 

开发步骤

  • 定义组件
<template>
    <div id="home">
        <h3>这是主页</h3>
    </div>
</template>
<template>
    <div id="news">
        <h3>这是新闻</h3>
    </div>
</template>

 

  • 定义URL和组件的跳转关系  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
        }
    ]
}

  

  • 在main.js中,创建路由实例,并在Vue实例中引入
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
import routerConfig from './router.config.js'
import axios from 'axios'

//使用VueRouter
Vue.use(VueRouter);


//创建路由实例
const router=new VueRouter(routerConfig);

Vue.prototype.$http=axios;

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

  

  • App,vue调用
<template>
  <div id="app">
    <h3>
      <router-link to="/home">主页</router-link>
      <router-link to="/news">新闻</router-link>
    </h3>
    <div>
      <keep-alive>
        <router-view></router-view>
      </keep-alive>
    </div>

    <hr>
    <button @click="send">发送AJAX请求</button>
    <MyButton @click.native="send">监听组件根元素的原生事件</MyButton>  
  </div>

</template>

<script>
import MyButton from "./components/MyButton.vue";
// import axios from "axios";

export default {
  name: "app",
  data() {
    return {};
  },
  mounted() {
    console.log(this.$route);
  },
  watch: {
    $route: function(newValue, oldValue) {
      console.log("路由发生变化,跳转到:" + newValue.path);
    }
  },
  components: {
    MyButton
  },
  methods: {
    send(){
      // axios.get("https://api.github.com/users/tangyang8942")
      this.$http.get("https://api.github.com/users/tangyang8942")
        .then(resp => {
          console.log(resp.data);
        }).catch(err => {
          console.log(err);
        })
    }
  }
};
</script>

<style>
</style>

 

其他注意的: 

  1. 使用axios的两种方式:1).在每个组件中引入axios   2).在main.js中全局引入axios并添加到Vue原型中
  2. 为自定义组件添加事件  .native--监听原生事件

 

登陆验证与页面跳转

  由于Vue是组件化思想,如果想实现类似刷新页面的效果,在根节点下App放个路由显示视图即可,组件注入则通过跳转url来实现

<template>
  <div id="app">
      <router-view></router-view>
  </div>
</template>

  

      path: "/",
      name: "index",
      component: IndexComp,
      children: [],
      meta: {
        requiresAuth: false
      }

 index.vue 

<template>
    <div>
        <button @click="redir">主页</button>
        <a href="/#/login">登陆</a>
    </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {};
  },
  methods: {
    redir() {
      this.$router.push({
        name: "home"
        // query:{}
      });
    }
  }
};
</script>

 

  而跳转url是否需要登陆验证,则通过router.beforeEach方法来实现

import Vue from 'vue'
import Router from 'vue-router'
import IndexComp from './components/index.vue'
import Home from './components/home.vue'
import Login from './components/login.vue'
import Store from './store.js';

Vue.use(Router)

const router = new Router({
  routes: [{
      path: "/",
      name: "index",
      component: IndexComp,
      children: [],
      meta: {
        requiresAuth: false
      }
    },
    {
      path: '/home',
      name: 'home',
      component: Home,
      meta: {
        requiresAuth: true,
      }
    }, {
      path: '/login',
      name: 'login',
      component: Login,
      meta: {
        requiresAuth: false,
      }
    }
  ]

})

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth === false) {
    next();
  } else {
    if (Store.state.isLogin === true) {
      next();
    } else {
      alert('请登陆...');
      next({
        path: '/login',
        query: {
          redirect: to.fullPath
        }
      })
    }
  }
})

export default router;

  

 

posted @ 2018-07-25 16:29  财经知识狂魔  阅读(291)  评论(0编辑  收藏  举报