`

electron.js数据库应用---导航菜单(element-ui+mysql)

阅读更多
一、环境搭建
  略,请见https://wallimn.iteye.com/blog/2437140

二、MySQL数据库脚本
create table t_menu(
    id int primary key auto_increment,
    tree_id int ,
    tree_pid int, 
    title varchar(60), 
    url varchar(255),
    target varchar(60), 
    icon varchar(255),
    remark varchar(255)
) default charset = utf8 ;

insert into t_menu(tree_id,tree_pid,title,url,target,icon,remark)
values(1,0,'系统管理','about:blank','main',null,null);

insert into t_menu(tree_id,tree_pid,title,url,target,icon,remark)
values(2,1,'用户管理','about:blank','main',null,null);

insert into t_menu(tree_id,tree_pid,title,url,target,icon,remark)
values(3,1,'角色管理','about:blank','main',null,null);

insert into t_menu(tree_id,tree_pid,title,url,target,icon,remark)
values(4,1,'功能管理','about:blank','main',null,null);

insert into t_menu(tree_id,tree_pid,title,url,target,icon,remark)
values(5,0,'业务管理','about:blank','main',null,null);

insert into t_menu(tree_id,tree_pid,title,url,target,icon,remark)
values(6,5,'JAVA业务','about:blank','main',null,null);

insert into t_menu(tree_id,tree_pid,title,url,target,icon,remark)
values(7,5,'JavaScript业务','about:blank','main',null,null);

insert into t_menu(tree_id,tree_pid,title,url,target,icon,remark)
values(8,5,'C#业务','about:blank','main',null,null);


二、后台JS
(一)数据库基础类db.js
var mysql = require('mysql');

// 创建一个数据库连接池
var pool = mysql.createPool({
  connectionLimit: 50,
  host:"127.0.0.1",
  port:"3306",
  user: "root",
  password: "",
  database: "test"
});

/**
 * 执行SQL,增、删、改、查全用这一个函数
 * 参数:
 *  sql:要执行的SQL语句
 *  P:参数,如果没有可不传,可以是数组或对象类型
 *  C:回调函数,执行成功后调用的语句
 */
exports.query = function (sql, P, C) {
  var params = [];
  var callback;

  if (arguments.length == 2 && typeof arguments[1] == 'function') {
    callback = P;
  } else if (arguments.length == 3 && Array.isArray(arguments[1]) && typeof arguments[2] == 'function') {
    params = P;
    callback = C;
  } else {
    //会导致程序崩溃退出。
    throw new Error('对不起,参数个数不匹配或者参数类型错误');
  }


  // 从池子里面拿一个可以使用的连接
  pool.getConnection(function (err, connection) {
    if(err){
      callback.apply(null,[err]);
      return;
    }
    
    connection.query(sql, params, function () {
      // 使用完毕之后,将该连接释放回连接池
      connection.release();
      callback.apply(null, arguments);
    });
  });
};


(二)后台服务类dbservice.js
var db = require("./db.js");

/*
 * 数据库服务类。
 */

/**
 *生成导航菜单
 *
 * @param {*} callback 回调函数
 */
function selectNavMenus(callback){
    db.query("select * from t_menu  order by tree_pid,tree_id",function(error,results){
        if(error){
            callback(error);
        }
        else{
            var treeArray = resultsToTreeArray(results);
            callback(null,treeArray);
        }
        //callback.apply(null,arguments);
    });
}

/**
 *转化为导航菜单使用的数组,只考虑了菜单分两级。
 *
 * @param {*} error
 * @param {*} results
 * @returns
 */
function resultsToTreeArray(results){
    var treeArray = [];
    var len = results.length;
    for(var i=0;i<len; i++){
        if(results[i].tree_pid===0){//根的ID为0
            results[i].children=[];
            treeArray.push(results[i]);
        }
    }
    for(var j=0; j<treeArray.length;j++){
        for(var i=0;i<len; i++){
            if(results[i].tree_pid===treeArray[j].tree_id){
                treeArray[j].children.push(results[i]);
            }
        }
    }
    return treeArray;
}


module.exports = {
    "selectNavMenus":selectNavMenus,
    "author":'wallimn',
    "version":'20190204'
}


三、前端页面navmenu.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>electron.js+mysql示例, by wallimn, 2019-02-05</title>
    <link rel="stylesheet" type="text/css" href="./libs/element-ui.v2.4.9/theme-chalk/index.css">
    <style>
        body,html,#app{
          height:100%;
          margin:0;
        }
      </style>
  </head>
  <body>
    <div id="app">
      <el-menu :default-active="activeIndex" class="el-menu-main" mode="horizontal" background-color="#545c64" text-color="#fff"
        active-text-color="#ffd04b" @select="handleSelect">
        <template v-for="item in menus">
          <template v-if="item.children.length==0">
            <el-menu-item :index="'mi'+item.id" :key="item.id">{{item.title}}</el-menu-item>
          </template>
          <template v-else>
            <el-submenu v-if="item.children.length>0" :index="'mi'+item.id" :key="item.id">
              <template slot="title">{{item.title}}</template>
              <el-menu-item v-for="subitem in item.children" :key="subitem.id" :index="'mi'+subitem.id">{{subitem.title}}</el-menu-item>
            </el-submenu>
          </template>
        </template>
      </el-menu>
    </div>
    
    <script type="text/javascript" src="./libs/vue.js"></script>

	  <!-- 引入组件库 -->
	  <script src="./libs/element-ui.v2.4.9/index.js"></script>
    <script type="text/javascript">
      // Vue实例化
      var doit = new Vue({
        el:'#app',
        data: function(){
          return {
            menus:[],
            activeIndex:"1",
            service:require('./dbservice.js')
          };
        },
        created:function(){
          this.loadMenuData();
        },
        methods: {
          loadMenuData:function(){
            var self = this;
            //var db = require('./db');
            self.service.selectNavMenus(function(err,rows){
              if(err){
                console.error(err);
              }
              else{
                var len = rows.length;
                self.menus = [];
                for(var i=0; i<len; i++ ){
                  self.menus.push(rows[i]);
                }
                if(len>0){
                  if(self.menus[0].children.length==0){
                    self.activeIndex="mi"+self.menus[0].id;
                  }
                  else{
                    self.activeIndex = "mi"+self.menus[0].children[0].id;
                  }
                  console.log("设置当前菜单:"+self.activeIndex);
                }
              }
            });

          }
        }	//end of methods		
      });
   
    </script>
  </body>
</html>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics