最新写 Vue 项目使用 ElementUI 做前端, 然后需要集成一个 vue Router, 主要功能是侧边栏不刷新而内容刷新, 看了几个 starter 都和需求不太一样, 因此干脆自己搞一个

Installation - Element UI

直接用的 element-starter

Installation - Vue Router

npm install vue-router

main.js

Entry 文件里面要进行修改, 将 vueRouter 用作插件, 并且引用 routes

这里进行了: 将 App 渲染到 #app

import Vue from 'vue'
import VueRouter from 'vue-router'

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import App from './App.vue'
import routes from './routes'

Vue.use(ElementUI)
Vue.use(VueRouter);

Vue.config.productionTip = false;

const router = new VueRouter({
  routes
});

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

app.vue

这个文件的核心就是要放一个 <router-view>

<template>
  <el-container>
    <router-view></router-view>
  </el-container>
</template>

(……)

routes.js

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

const routes = [{
    path: '/',
    component: Home
  },
  {
    path: '/tags',
    component: Tags
  },
];

export default routes;

Home.vue

最后准备下几个不同的 components 即可, 下面是一个例子

// Home.vue

<template>
  <div>
    Home
  </div>
</template>
<script>
  export default {

  }
</script>

路由强制刷新

有时候会出现这样的情况: 在使用 Vue-router 做项目时, 会遇到如 /user/:id 这样只改变 id 号. 由于 router-view 是复用的, 单纯的改变 id 号并不会刷新 router-view, 而这并不是我们所期望的结果

我们就需要用一些办法在 route pattern 不改变的情况强制刷新:

  1. 使用 activated 周期函数代替 mounted 函数

    • 不推荐, 导致不必要的刷新
  2. Watch: 直接给模板添加 watch

    watch: {
      '$route': function(to, from) {
        // 我这里还是用了 Vuex,不过应该不影响理解
        this.$store.dispatch('updateActiveTemplateId', this.$route.params.templateId)
        // 通过更新 Vuex 中的 store 的数据,让数据发生变化
        this.getTemplateById()
      }
    },
    
  3. beforeRouteLeave

    beforeRouteUpdate(to, from, next) {
      // 在当前路由改变,但是该组件被复用时调用
      // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
      // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
      // 可以访问组件实例 `this` 
    },
    

源码

https://github.com/szhshp/Vue-ElementUI-Router