一個小白的vue之路(四)——搭建自己的後臺管理開發框架(1)

複雜動物發表於2018-12-17

前言:本文我們來一起動手搭建自己的後臺管理開發框架,主要目的是為了加深對VUE框架理解與使用。我們在本文中要實現後臺管理模板最基本的功能,登陸進入主頁,點選主頁左側選單動態載入右側內容。本文中會用到幾個vue的幾個主要外掛,只簡單介紹其用法,不做深入。另外本文不涉及頁面樣式只注重功能,在後面的文章中我們會引入element-ui、登陸驗證、許可權控制等,最終形成一套完整的後臺管理模板。

第一步 開始前準備:

涉及的外掛:

vue-router:是 Vue.js 官方的路由管理器。
vuex、vuex-persistedstate:每一個 Vuex 應用的核心就是 store(倉庫)。“store”基本上就是一個容器,它包含著你的應用中大部分的狀態 (state)。vuex-persistedstatevuex的一個狀態持久化外掛。
axios:Axios 是一個基於 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。(發起Ajax請求)。
mock.js:生成隨機資料,攔截Ajax請求。

所需頁面:

login.vue, mainboard.vue , modulelist.vue , userlist.vue

第二步:開搞

建立相關頁面
login.vue:

<template>
  <div>
    使用者名稱:
    <input type="text" v-model="user.username">
    <br>密碼
    <input type="password" v-model="user.password">
    <br>
    <span :style="{'display':isSuccess?'none':'block','color':'red'}">登陸失敗
      <br>
    </span>
    <button type="button" @click="login">登陸</button>
  </div>
</template>
<script>
import { mapMutations } from "vuex";
//import systemapi from "../api/system.js";

export default {
  data() {
    return {
      isSuccess: true,
      user: {
        username: "",
        password: ""
      }
    };
  },
  methods: {
    login() {
      //返回的資訊存起來
      //頁面跳轉
      //
      //console.log(this.user);
      this.axios
        .post("/login", this.user)
        .then(data => {
          console.log(data)
          this.setModuleList(data.data.moduleList);
          this.$router.push("/mainboard");
        })
        .catch(() => {
          this.isSuccess = false;
        });
      // systemapi.login(this.user,(data)=>{
      //   this.setModuleList(data.moduleList);
      //   this.$router.push("/mainboard");
      // },()=>{
      //   this.isSuccess = false;
      // });
    },
    ...mapMutations([
        "setModuleList"
    ])
  }
};
</script>


mainboard.vue:

<template>
    <div>
        <h1>{{aa}}</h1>
        <div class="left">
            <ul>
                <li v-for="item in modulelist" :key="item.id"><router-link :to="item.path">{{item.name}}</router-link></li>
            </ul>
        </div>
        <div class="right">
            <router-view></router-view>
        </div>
    </div>
</template>

<script>
import {mapState} from "vuex";
//import systemapi from "../api/system.js";
export default {
    data(){
        return{
            aa:10
        }
    },
    methods:{
        
    },
    mounted:
        function getAA(){
            this.axios.get('/getaa').then(data=>{
                this.aa=data.data.aa
            }).catch() 
            //this.aa=systemapi.getAA();
        },
    
    computed:{
        ...mapState([
            "modulelist","m2","m3"
        ])
    }
}
</script>


<style scoped>
.left,.right{
    float:left;
    box-sizing: border-box;
    padding:50px;
}
</style>


modulelist.vue:

<template>
    <div>
        <table>
            <tr>
                <th>模組名稱</th>
                <th>url地址</th>
            </tr>
            <tr v-for="item in modulelist" :key="item.id">
                <td>{{item.name}}</td>
                <td>{{item.path}}</td>
            </tr>
        </table>
    </div>
</template>
<script>
export default {
    data(){
        return {
            modulelist:[]
        }
    },
    created(){
        //發起請求
        //this.modulelist = data;
        this.axios.get("/getUserList").then((data)=>{
            this.modulelist = data.data;
        });
    }
}
</script>


userlist.vue:

<template>
  <div>
    <table>
      <tr>
        <th>使用者名稱稱</th>
        <th>角色</th>
      </tr>
      <tr v-for="item in userlist" :key="item.id">
        <td>{{item.name}}</td>
        <td>{{item.role}}</td>
      </tr>
    </table>
  </div>
</template>
<script>
export default {
  data() {
    return {
      userlist: []
    };
  },
  created() {
    //發起請求
    //this.userlist = data;
    this.axios.get("/getUserList").then(data => {
      this.userlist = data.data;
    });
  }
};
</script>


引入vue-router
router.js

import VueRouter from "vue-router";
import Vue from "vue";
import login from "../views/login.vue";
import mainboard from "../views/mainboard.vue";
import modulelist from "../views/modulelist.vue";
import userlist from "../views/userlist.vue";
Vue.use(VueRouter);
const router = new VueRouter({
    routes:[
        {
            path:"/",
            component:login
        },
        {
            path:"/mainboard",
            component:mainboard,
            children:[
                {
                    path:"modulelist",
                    component:modulelist
                },
                {
                    path:"userlist",
                    component:userlist
                }
            ]
        }
    ]
});

export default router;

引入vuexvuex-persistedstate:
store.js:

import Vuex from "vuex";
import Vue from "vue";
import createPersistedState from 'vuex-persistedstate';
Vue.use(Vuex);
const store = new Vuex.Store({
    state:{
        modulelist:[]
    },
    mutations:{
        setModuleList(state,list){
            //localStorage.setItem("modulelist",JSON.stringify(list));
           // createPersistedState.setModuleList(list);

            state.modulelist = list;
        }
    },
    plugins:[
        createPersistedState()
    ]
});

export default store;

mock.js:

import Mock from "mockjs";

Mock.mock("/login", "post", {
    username: "zhang",
    rolename: "admin",
    moduleList: [{
            id: 0,
            name: "選單模組",
            path: "/mainboard/modulelist"
        },
        {
            id: 1,
            name: "使用者模組",
            path: "/mainboard/userlist"
        }
    ]
});
Mock.mock("/getaa","get",{aa:20})
Mock.mock("/getModuleList", "get", [{
        id: 0,
        name: "選單模組",
        path: "/mainboard/modulelist"
    },
    {
        id: 1,
        name: "使用者模組",
        path: "/mainboard/userlist"
    }
])

Mock.mock("/getUserList", "get", [{
        id: 0,
        name: "zhang",
        role: "admin"
    },
    {
        id: 1,
        name: "li",
        role: "guest"
    }
])

main.js:

import Vue from 'vue'
import App from './App.vue'
import router from "./config/router.js";
import VueAxios from "vue-axios";
import axios from "axios";
import "./config/mock.js";
import store from "./store/store.js";

Vue.use(VueAxios,axios);
Vue.$http = axios;

Vue.config.productionTip = false

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

ok,完成!當然每個外掛都有自己更高階的用法,希望大家去多多學習

相關文章