SpringBoot2+Vue2实战(四)进行组件内容拆分及路由实现

一、拆分

新建包:

Aside和Header都是组件

User为视图

SpringBoot2+Vue2实战(四)进行组件内容拆分及路由实现_第1张图片

 Aside.vue:





Head.vue





User.vue

拆出页面布局及方法





Manage.vue

调用拆分的视图及组件

视图:使用router-view调用

组件:导入组件包:

//导入
import Aside from "@/components/Aside.vue";
import Header from "@/components/Header.vue";

创建组件包含内容

//调用组件
  components: {
    Aside,
    Header,
  },

调用组件:


      




router/index.js

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

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: () => import('../views/Manage.vue'),
    redirect:"/home",
    children:[
      {path: 'user', name: '用户管理', component: () => import('../views/User.vue'),},
      {path: 'home', name: '首页', component: () => import('../views/Home.vue'),}

    ]
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('../views/AboutView.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

Vue路由使用:

Aside:





router/index.js

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

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: () => import('../views/Manage.vue'),
    redirect:"/home",
    children:[
      {path: 'user', name: '用户管理', component: () => import('../views/User.vue'),},
      {path: 'home', name: '首页', component: () => import('../views/Home.vue'),}

    ]
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('../views/AboutView.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

/*// 路由守卫
router.beforeEach((to, from, next) => {
  localStorage.setItem("currentPathName", to.name)  // 设置当前的路由名称,为了在Header组件中去使用
  store.commit("setPath")  // 触发store的数据更新
  next()  // 放行路由
})*/

export default router

Head.vue






Vuex下载

npm i vuex -S

store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        currentPathName: ''
    },
    mutations: {
        setPath (state) {
            state.currentPathName = localStorage.getItem("currentPathName")
        }
    }
})

export default store

main.js

import store from './store'


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

你可能感兴趣的:(vue.js,javascript,elementui)