如何在传统前后端不分离的项目中使用模块化开发方式写.vue格式文件

项目情况

项目是c#的三层架构技术搭建的,前端这一块是在.aspx页面中以script标签引入js <link rel="stylesheet">方式引入css的方式来开发的后台系统网站。

网站整体界面结构如下图

QQ图片20190719102256

左侧是菜单,右侧是主题内容页面,主题内容是嵌入在一个iframe中,通过点击左侧菜单,切换iframe的src在显示不同的页面。

vue 单文件形式开发

思路

- 1. 页面的右侧部分提供一个占位符节点,这个节点用 Vue 渲染,实际上就是执行一段 JS 代码

- 2. 通过webpack配置一个vue项目,打包出一段JS。然后再右侧的页面中引入这个js

具体实践

项目目录

QQ图片20190719104003

新建一个目录vueDevInstanceModule,通过配置webpack构建vue项目的代码全放到里面

webpack相关使用请去看文档

下面是我这个项目中配置好的packjson.json与webpack.config.js
packjson.json

{
  "name": "webpack-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "watch": "webpack --watch",
    "start": "webpack-dev-server --open",
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.4.5",
    "@babel/plugin-syntax-dynamic-import": "^7.2.0",
    "@babel/plugin-transform-runtime": "^7.4.4",
    "@babel/preset-env": "^7.4.5",
    "babel-loader": "^8.0.6",
    "clean-webpack-plugin": "^3.0.0",
    "copy-webpack-plugin": "^5.0.3",
    "extract-text-webpack-plugin": "^3.0.2",
    "html-webpack-plugin": "^3.2.0",
    "vue-loader": "^15.7.0",
    "vue-template-compiler": "^2.6.10",
    "webpack": "^4.35.2",
    "webpack-bundle-analyzer": "^3.3.2",
    "webpack-cli": "^3.3.5",
    "webpack-dev-server": "^3.7.2"
  },
  "dependencies": {
    "vue": "^2.6.10",
    "vue-router": "^3.0.6"
  }
}
View Code

webpack.config.js

const path = require('path');
// const CleanWebpackPlugin = require('clean-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
// var ExtractTextPlugin = require("extract-text-webpack-plugin")
var MiniCssExtractPlugin = require("mini-css-extract-plugin")

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; //分析js文件大小情况

function resolve(dir) {
  return path.join(__dirname, '..', dir)
}


console.log('---------------------------->', path.join(__dirname, 'dist'))

//配置输出文件目录
// const outputSrc = './dist/baseinfo';
const outputSrc = './dist/agent';
createOutputSrc(outputSrc)

function createOutputSrc(outputSrc) {

  var fs = require('fs');
  if (!fs.existsSync(outputSrc)) {
    fs.mkdirSync(outputSrc);
  }
}

module.exports = {
  mode: 'production', //development
  entry: './src/main.js',
  devtool: 'inline-source-map',
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      title: '管理输出',
      template: 'index.html',
    }),
    new VueLoaderPlugin(),
    
    new MiniCssExtractPlugin({
      filename: 'style.css'
    }),
   
    // new CopyWebpackPlugin([ // 拷贝暂时先不要,后面需要用到静态文件时在考虑
    //     {
    //       from: path.resolve(__dirname, 'src'),
    //       to: outputSrc,
    //       ignore: ['.*']
    //     }
    //   ])
    // new BundleAnalyzerPlugin()
  ],
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      //   'vue$': 'vue/dist/vue.esm.js',  3.0 写法
      //   '@': resolve('src'),
      //   components: resolve('src/components'),
      src: path.resolve(__dirname, './src/'),
      components: path.resolve(__dirname, './src/components/')
    }
  },
  module: {
    rules: [
      { 
        test: /\.vue$/, 
        loader: 'vue-loader',
        options: {
          extractCSS: true
        }
      },
      {
        test: /\.m?js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
            // plugins: ['@babel/plugin-transform-runtime']
          }
        }
      },
   
      {
        test: /.css$/,
        use: [
          {loader: 'vue-style-loader'},'css-loader'
        ]
      },
    ]
  },
  devServer: {
    port: 8889,
    contentBase: path.join(__dirname, 'dist'), //对那个目录起服务 并监听文件变化更新代码
    // publicPath: '/' //webpack-dev-server 在编译之后不会写入到任何输出文件。而是将 bundle 文件保留在内存中 如果你的页面希望在其他不同路径中找到 bundle 文件,则可以通过 dev server 配置中的 publicPath 选项进行修改。
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, outputSrc) //'dist/'
   
  },

  optimization: {
    splitChunks: {
      cacheGroups: {
        default: false,
        vendors: false,
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all',
        },
      }
    }
  }
};
View Code

tips:

webpack相关配置已经配置好了,目前能够做到编写vue文件保存后就会自动编译为js,然后在对应的aspx页面引入这个js就行了。

这里以我的项目为例

运行项目与配置

1.运行后台项目,以新增代理商页面为例 打开地址`http://localhost:31545/riskManage/Agent/AgentAdd/#/`后

2.进入项目的`vueDevInstanceModule\webpack-project`目录下执行npm run watch,会自动打包出出vendors.js,main.js到`dist/agent`目录下,

3.AgentAdd.aspx页面底部引入vendors.js,main.js

AgentAdd.aspx

<script src="~/vueDevInstanceModule/webpack-project/dist/agent/vendors.js"></script>

<script src="~/vueDevInstanceModule/webpack-project/dist/agent/main.js"></script>

4.配置不同模块输出

多人协作每个人写不同的模块时,例如A写代理商模块,B写用户基本信息模块,分别只打包自己写的代码

#以新增一个用户信息模块为例,需要做以下4

(1).修改webpack的输出地址

webpack.config.js

const outputSrc = './dist/baseInfo';

 

(2).复制一份路由router.js文件做好页面文件引入

// import Vue from 'vue'

import Router from 'vue-router'

import BaseInfo from 'components/baseInfo/addInfo'

import InfotList from 'components/baseInfo/InfoList'

Vue.use(Router)

(3).main.js中引入刚刚那个路由

import router from "./router/baseInfoRoute" //路由文件,

(4).useInfo.aspx页面引入

<script src="~/vueDevInstanceModule/webpack-project/dist/baseInfo/vendors.js"></script>

<script src="~/vueDevInstanceModule/webpack-project/dist/baseInfo/main.js"></script>

 

最后的特别说明

该方式目前只实现了把.vue文件中的html,js打包出js文件,css,img资源暂未做处理。因此css还是去以前的地方(`E:\myWork\Allpro\trunk\E8Management\E8Management\Content\asset\css`)写吧

对了,watch的时候打包出的js想时时看效果需要强制刷新一下(ctrl+f5),由于没有做文件hash生成动态注入script标签到aspx中,我也想做呀,但是不好做。

还有不能使用异步加载路由,因为单独打包出来的xx.js个main.js不能一块放到aspx页面的同级main.js加载不到xx.js,这个可能是这里的后端三层构架view层解析的时候路由映射文件我所不知道的规则导致

结束~~

 

补充其他非.vue格式打包成js的开发模式

vue script标签引入的非webpack打包的形式开发
参考代码

 

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta charset="utf-8">
    <meta name="description" content="Admin Template v.1">
    <meta name="author" content="Isna Nur Azis">
    <meta name="keyword" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>AgentList</title>

    <!-- start: Css -->
    <link rel="stylesheet" type="text/css" href="~/Content/asset/css/bootstrap.min.css">
    <!-- plugins -->
    <link rel="stylesheet" type="text/css" href="~/Content/asset/css/plugins/font-awesome.min.css" />
    <link rel="stylesheet" type="text/css" href="~/Content/asset/css/plugins/simple-line-icons.css" />
    <link rel="stylesheet" type="text/css" href="~/Content/asset/css/plugins/animate.min.css" />
    <link rel="stylesheet" type="text/css" href="~/Content/asset/css/plugins/fullcalendar.min.css" />
    <link rel="stylesheet" type="text/css" href="~/Content/asset/css/plugins/bootstrap-material-datetimepicker.css" />
    <link href="~/Content/asset/css/style.css" rel="stylesheet">
    <!-- end: Css -->
    <link rel="shortcut icon" href="~/Content/asset/img/logomi.png">
    <link href="~/Content/datetimepicker/datetimepicker.css" rel="stylesheet" />

    <link href="~/Content/asset/js/plugins/自动完成下拉选择--支持中文/css/selectpage.css" rel="stylesheet" />

    <!-- start: Javascript -->
    <script src="~/Content/asset/js/jquery.min.js"></script>
    <script src="~/Content/asset/js/jquery.ui.min.js"></script>
    <script src="~/Content/asset/js/bootstrap.min.js"></script>
    <script src="~/Content/asset/layer/layer.js"></script>
    <script src="~/Content/datetimepicker/datetimepicker.js"></script>
    <script src="~/Content/asset/js/plugins/citySelect/distpicker.data.js"></script>
    <script src="~/Content/asset/js/plugins/citySelect/distpicker.js"></script>
    @*<script src="~/Content/asset/js/plugins/自动完成下拉选择--支持中文/js/jquery-1.11.0.min.js"></script>*@
    <script src="~/Content/asset/js/plugins/自动完成下拉选择--支持中文/js/selectpage.js"></script>
    <!-- plugins -->
    <script src="~/Content/asset/js/plugins/moment.min.js"></script>
    <script src="~/Content/asset/js/plugins/fullcalendar.min.js"></script>
    <script src="~/Content/asset/js/plugins/jquery.nicescroll.js"></script>
    <script src="~/Content/asset/js/plugins/jquery.vmap.sampledata.js"></script>
    <script src="~/Content/asset/js/plugins/bootstrap-material-datetimepicker.js"></script>
    <script src="~/Content/asset/js/plugins/vue2.4.js"></script>
    <script src="~/Content/asset/js/cmn/Cmn.js"></script>
    <script src="~/Content/asset/js/cmn/CmnAjax.js"></script>
    <script src="~/Content/asset/js/cmn/CmnFuncExd.js"></script>
    <script src="~/Content/asset/js/utils/utils.js"></script>
    <style>
        /*.part_box{display:none;}*/
        .disabled {
            pointer-events:none;
            /*cursor:not-allowed;*/
        }
    </style>
</head>

<body>
    <div id="myMenu" style="position:relative;z-index:0;">
        <div v-show="IsShow" class="part_box" style="display:none;">
            <div class="panel box-shadow-none content-header">
                <div class="panel-body">
                    <div class="col-md-12">
                        <h4 class="animated fadeInLeft" style="margin:0px;margin-top:5px; padding:0px;"><span>风控管理</span> <span class="fa-angle-right fa"></span> <span>代理商管理</span></h4>
                    </div>
                </div>
            </div>
            <div class="my-title1">查询条件</div>
            <div class="col-md-12 clearfix">
                <div lass="panel" style="margin:10px 0;">
                    <div class="panel-body bg-white">
                        <table style="width:100%">
                            <tr class="row">
                                <td class="col-md-4">
                                    <label class="control-label">代理商名称</label>
                                    <div class="form-group">
                                        <input type="text" class="form-control" id="AgentName">
                                    </div>
                                </td>
                                <td class="col-md-4">
                                    <label class="control-label">上级代理商名称</label>
                                    <div class="form-group">
                                        <input type="text" class="form-control" id="ParentAgentName">
                                    </div>
                                </td>
                                <td class="col-md-4">
                                    <label class="control-label" for="Name">是否为任意通返利代理商</label>
                                    <div class="form-group">
                                        <select class="form-control" id="IsRebate">
                                            <option value="-1">请选择</option>
                                            <option value="1"></option>
                                            <option value="0"></option>
                                        </select>
                                    </div>
                                </td>
                                <td class="col-md-4"></td>
                            </tr>
                            <tr>
                                <td colspan="3">
                                    <input type="button" class="btn btn-primary" value="查询" id="selData">
                                </td>
                            </tr>
                        </table>

                    </div>
                </div>
            </div>
            <div class="my-title1">代理商列表</div>
            <div class="col-md-12 mt10">
                <div class="panel">
                    <div class="panel-body">
                        <div class="responsive-table" style="width:100%;overflow:auto;">
                            <div class="table-title-btn-wrap">
                                <div class="table-title-btn-box">

                                    <input type="button" class="btn btn-primary" value="添加" id="addnew" v-on:click="goToadd(0);">
                                </div>
                            </div>
                            <table class="table table-striped table-bordered" cellspacing="0">
                                <thead>
                                    <tr>
                                        <th style="min-width:80px;">ID</th>
                                        <th style="min-width:100px;">代理商名称</th>
                                        <th style="min-width:100px;">上级代理商名称</th>
                                        <th style="min-width:80px;">是否为任意通返利代理商</th>
                                        <th style="min-width:100px;">创建时间</th>

                                        <th style="min-width:100px;">创建人</th>
                                        <th style="min-width:100px;">最后操作时间</th>
                                        <th style="min-width:100px;">最后操作人</th>

                                        <th style="min-width:80px;">操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr class="Js_tableDataList">
                                        <td>{Id}</td>
                                        <td>{AgentName}</td>
                                        <td>{ParentAgentName}</td>

                                        <td>{IsRebate}</td>
                                        <td>{CreateTime}</td>

                                        <td>{CreateUserName}</td>
                                        <td>{UpdateTime}</td>

                                        <td>{UpdateUserName}</td>
                                        <td>
                                            <input type="button" class="btn btn-primary js_editOrPreview" value="编辑" data-id="{Id}" data-type="edit" v-on:click="editOrPreview('edit',{Id});">
                                            <input style="margin-left:15px;" type="button" class="btn btn-primary js_editOrPreview" value="查看详情" data-id="{Id}" data-type="preview" v-on:click="editOrPreview('preview',{Id});">
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div class="col-md-12">
                            <ul class="pagination pull-right">
                                <li class="list_page_box">

                                    <div class="" style="position:absolute;left:0px;top:20px;">
                                        <select style="width:100px;padding:5px;margin-right:10px;" id="exchangePageSize">
                                            <option value="10">每页10条</option>
                                            <option value="20">每页20条</option>
                                            <option value="30">每页30条</option>
                                            <option value="40">每页40条</option>
                                            <option value="50">每页50条</option>
                                        </select><a href="javascript:void(0)" class="pagCount" style="margin-left:5px;"></a>页,
                                        <a href="javascript:void(0)" class="js_RecCount" style="margin-left:5px;"></a></div>
                                    <a href="javascript:void(0)" class="pagFirst">首页</a>
                                    <a href="javascript:void(0)" class="pagPre"><span aria-hidden="true">&laquo;</span></a>
                                    <a href="javascript:void(0)" class="pagNum active">1</a>

                                    <a href="javascript:void(0)" class="pagNext"><span aria-hidden="true">&raquo;</span></a>
                                    <a href="javascript:void(0)" class="pagLast"><span aria-hidden="true">尾页</span></a>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div v-show="!IsShow" class="part_box" style="display:none;">
            <div class="panel box-shadow-none content-header">
                <div class="panel-body">
                    <div class="col-md-12">
                        <h4 class="animated fadeInLeft" style="margin:0px;margin-top:5px; padding:0px;"><span>风控管理</span> <span class="fa-angle-right fa"></span> <span>代理商管理</span></h4>
                    </div>
                </div>
            </div>
            <div class="col-md-12 mt10">
                <div class="panel">
                    <div class="my-title2">代理商信息</div>
                    <div class="panel-body">
                        <table style="width:100%">
                            <tr>

                                <td class="col-md-6" style="height:72px;">
                                    <div id="covDatgeWrap" style="height:27px;">
                                        <div class="form-group form-animate-text " style="margin-top:-1px !important;">
                                            <input type="text" class="form-text mask-money " required="" id="AgentName_form" autocomplete="off">
                                            <span class="bar"></span>
                                            <label class="label">代理商名称</label>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td class="col-md-6">
                                    <label class="control-label label3">是否有上级代理商</label>
                                    <div class="form-group">
                                        <select id="IsHaveParent" name="IsHaveParent" class="dropdown-toggle form-control no_border2">
                                            <option value="1"></option>
                                            <option value="0"></option>
                                        </select>
                                    </div>
                                </td>
                                <td class="col-md-6" v-show="isHaveParent==1">
                                    <div class="form-group form-animate-text select-box2" style="margin-top:10px !important;">
                                        <input type="text" class="form-text mask-money" required="" id="ParentAgentName_form" placeholder="" style="height: 50px;">
                                        <span class="bar"></span>
                                        <label class="label select-label default">上级代理商</label>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td class="col-md-6">
                                    <label class="control-label label3">是否为任意通返利代理商</label>
                                    <div class="form-group">
                                        <select id="IsRebate_form" name="IsRebate" class="dropdown-toggle form-control no_border2">
                                            <option value="1"></option>
                                            <option value="0"></option>
                                        </select>
                                    </div>
                                </td>
                                <td class="col-md-6" style="height:72px;" v-show="isRebate==1">
                                    <div id="covDatgeWrap">
                                        <div class="form-group form-animate-text " style="margin-top:-1px !important;margin-bottom:-12px !important">
                                            <input type="text" class="form-text mask-money ChoiceTime" required="" id="RebateDate" autocomplete="off">
                                            <span class="bar"></span>
                                            <label class="label">返利起始日期</label>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <tr></tr>
                        </table>
                    </div>
                </div>
            </div>
            <div>
                <div class="col-md-12 mt10" id="panelContent">

                    <div class="panel  clearfix">
                        <div class="my-title2">业务联系人信息</div>
                        <div class="panel-body jspanel">
                            <div id="PanelEidt" style="padding-left:0px;" class="col-md-12">
                                <div class="form-group form-animate-text col-md-6" style="margin-top:10px !important;">
                                    <input type="text" class="form-text mask-money ConName" required="">
                                    <span class="bar"></span>
                                    <label>姓名</label>
                                </div>
                                <div class="form-group form-animate-text col-md-6" style="margin-top:10px !important;">
                                    <input type="text" class="form-text mask-money Phone" required="">
                                    <span class="bar"></span>
                                    <label>手机</label>
                                </div>
                                <div class="form-group form-animate-text col-md-6" style="margin-top:10px !important;">
                                    <input type="text" class="form-text mask-money Email" required="">
                                    <span class="bar"></span>
                                    <label>邮箱</label>
                                </div>
                                <div class="form-group form-animate-text col-md-6" style="margin-top:10px !important;">
                                    <input type="text" class="form-text mask-money QQNum" required="">
                                    <span class="bar"></span>
                                    <label>QQ/微信</label>
                                </div>
                            </div>
                        </div>
                        <div>
                        </div>
                    </div>

                </div>
                <input type="button" value="添加联系人" id="AddConMan" style="float:right;margin:6px 15px ;margin-right:43px;" class="btn btn-primary" v-show="!currentPreviewId">
            </div>

            <div class="col-md-12 mt10">
                <div class="panel">
                    <div class="panel-body"  v-show="!currentPreviewId">
                        <input type="button" value="提交" id="AddBtn" class="btn btn-primary" v-on:click="agentSave();" v-show="!currentEditId" />
                        <input type="button" value="确定" id="AddBtn" class="btn btn-primary" v-on:click="agentSave();" v-show="currentEditId" />
                        <input type="button" value="返回" id="backBtn" class="btn btn-primary" style="margin-left:20px;" v-on:click="backBtn();" />

                    </div>
                    <div class="panel-body" v-show="currentPreviewId">
                        <input type="button" value="返回" id="backBtn" class="btn btn-primary" style="margin-left:20px;" v-on:click="backBtn();" />

                    </div>
                    
                </div>
                <div style="height:100px;"></div>
            </div>
        </div>



    </div>
    <script type="text/javascript">
        $(function () {
            
            //列表相关-----start
            var exchangePageSize = localStorage.getItem('exchangePageSize') || 10; ///modify
            $("#exchangePageSize").val(exchangePageSize)

            var serchParams = {
                AgentName: $("#AgentName").val(),
                ParentAgentName: $("#ParentAgentName").val(),
                IsRebate: $("#IsRebate").val()
            }
            DataPagingTableDataList(serchParams, exchangePageSize);
            $("body").on('click', '#selData', function () {
                var exchangePageSize = localStorage.getItem('exchangePageSize') || 10; ///modify
                $("#exchangePageSize").val(exchangePageSize)
                var serchParams = {
                    AgentName: $("#AgentName").val(),
                    ParentAgentName: $("#ParentAgentName").val(),
                    IsRebate: $("#IsRebate").val()
                }
                DataPagingTableDataList(serchParams, exchangePageSize);
                //setInputsValueToStorge(); //设置值
            });

            $("#exchangePageSize").change(function () {
                var exchangePageSize = $("#exchangePageSize").val();
                var serchParams = {
                    AgentName: $("#AgentName").val(),
                    ParentAgentName: $("#ParentAgentName").val(),
                    IsRebate: $("#IsRebate").val()
                }
                DataPagingTableDataList(serchParams, exchangePageSize);
                localStorage.setItem('exchangePageSize', exchangePageSize) ///add
            });
        })
        
        //消息翻页
        function DataPagingTableDataList(params, exchangePageSize) {
           
            _dataPaging = new CmnAjax.DataPaging(".Js_tableDataList", "/Agent/GetAgentList", params, ".list_page_box", exchangePageSize, function (data) {
                $('.js_RecCount').html(data.RecCount)
                window.parent.postMessage("dataLoadSuccess", '*');
            }, function (data) { //填充数据之前的处理
                $.each(data.data, function (i, item) {
                    if (item.IsRebate == "1") {
                        item.IsRebate = "";
                    }
                    else if (item.IsRebate == "0") {
                        item.IsRebate = "";
                    }
                });
            });
            _dataPaging.Paging.ActiveClass = "active";
            _dataPaging.Paging.SetCycleNextPre(true);
        }

        function createContactList() {
            $("#panelContent").append("<div class='panel jspanel js_clonejspanel'> " +
                                           " <div class='panel-body'>" +
                                               "<div id=\"PanelEidt\" style=\"padding-left:0px;\" class=\"col-md-12\">" +
                                    "                            <div class=\"form-group form-animate-text col-md-6\" style=\"margin-top:10px !important;\">" +
                                    "                                <input type=\"text\" class=\"form-text mask-money ConName\" required=\"\">" +
                                    "                                <span class=\"bar\"></span>" +
                                    "                                <label>姓名</label>" +
                                    "                            </div>" +
                                    "                            <div class=\"form-group form-animate-text col-md-6\" style=\"margin-top:10px !important;\">" +
                                    "                                <input type=\"text\" class=\"form-text mask-money Phone\" required=\"\">" +
                                    "                                <span class=\"bar\"></span>" +
                                    "                                <label>手机</label>" +
                                    "                            </div>" +
                                    "                            <div class=\"form-group form-animate-text col-md-6\" style=\"margin-top:10px !important;\">" +
                                    "                                <input type=\"text\" class=\"form-text mask-money Email\" required=\"\">" +
                                    "                                <span class=\"bar\"></span>" +
                                    "                                <label>邮箱</label>" +
                                    "                            </div>" +
                                    "                            <div class=\"form-group form-animate-text col-md-6\" style=\"margin-top:10px !important;\">" +
                                    "                                <input type=\"text\" class=\"form-text mask-money QQNum\" required=\"\">" +
                                    "                                <span class=\"bar\"></span>" +
                                    "                                <label>QQ/微信</label>" +
                                    "                            </div>" +
                                    "                        <input type='button' value='删除联系人' onclick='DelPanel(this)' class='btn btn-primary mt10 js_clone_delect' style='float:right;' /></div>" +
                                           "</div>" +
                                      " </div>")
        }
        $("body").on('click', '#AddConMan', function () {
            if ($(".jspanel").length >= 4) {
                layer.msg('不能再添加更多了。')
                return false;
            }
            createContactList()
            //刷新页面高度
            window.parent.postMessage({ "dataLoadSuccess": "true" }, '*');
        });

        function DelPanel(doc) {
            var Obj = $(doc).closest(".jspanel");
            Obj.remove();
            window.parent.postMessage({ "dataLoadSuccess": "true" }, '*');
        }
       
       // function initVue() {
            //列表相关-----end
            //全局定义编辑器相关变量

            //var curPageIndex = null;
            var CustomerNameSelectPage = null;
            //初始化vue节点
            var vm = new Vue({
                el: '#myMenu',
                data: {
                    IsShow: true,
                    currentEditId: null,
                    currentPreviewId:null,
                    curPageIndex: null,
                    isHaveParent: 1,
                    isRebate: 1,
                },
                mounted: function () {
                    this.editOrPreview();
                    this.initDomEvent();
                },
                methods: {
                    agentSave: function (type) {
                        var that = this;
                        var scrollTop = $(window.parent.document).scrollTop() + 200;

                        var AgentName = $.trim($("#AgentName_form").val());
                        var IsHaveParent = $.trim($("#IsHaveParent").val());
                        var ParentID = $.trim($("#ParentAgentName_form").val());
                        var IsRebate = $.trim($("#IsRebate_form").val());
                        var RebateDate = $.trim($("#RebateDate").val());

                        if (!AgentName) {
                            layer.msg("请输入代理商");
                            return;
                        }
                        if (IsHaveParent == 1 && !ParentID) {
                            layer.alert('请输入上级代理商', { offset: scrollTop + 'px' });
                            return;
                        }
                        if (IsRebate == 1 && !RebateDate) {
                            layer.alert('请输入返利起始日期', { offset: scrollTop + 'px' });
                            return;
                        }
                        if (IsRebate == 1) {
                            //var _getNowDate = getNowDate();
                            
                            var getNowDateTime = new Date(getNowDate()).getTime();
                            var rebateDateTime = new Date(RebateDate).getTime();
                            if (rebateDateTime - getNowDateTime < 0) {
                                layer.alert('选择的返利起始日期必须大于等于今天', { offset: scrollTop + 'px' });
                                return;
                            }
                        }
                        var data = [];
                        $(".jspanel").each(function (i, item) {
                            var obj = {
                                ConName: $(item).find('.ConName').val(),
                                Phone: $(item).find('.Phone').val(),
                                Email: $(item).find('.Email').val(),
                                QQNum: $(item).find('.QQNum').val()
                            }
                            data.push(obj)
                        })
                        var params = {
                            AgentName: AgentName,
                            IsHaveParent: IsHaveParent,
                            IsRebate: IsRebate,
                            ParentID: ParentID,
                            RebateDate: RebateDate,
                            Data: data
                        }
                        var url = '/Agent/AgentAddSave';
                        if (this.currentEditId) { //如果currentEditId存在表示编辑
                            params.id = this.currentEditId;
                            url = '/Agent/AgentUpdateSave'
                        }
                        $.ajax({
                            url: url,
                            data: params,
                            type: 'post',
                            success: function (data) {
                                if (data.result) {
                                    layer.msg(data.msg, { offset: scrollTop + 'px' });
                                    //返回列表并刷新
                                    that.IsShow = true
                                    var exchangePageSize = localStorage.getItem('exchangePageSize') || 10; ///modify
                                    $("#exchangePageSize").val(exchangePageSize)
                                    DataPagingTableDataList({ EmailType: $("#EmailSendType").val() }, exchangePageSize);
                                    if (that.currentEditId && that.curPageIndex) {//如果是是编辑且列表不是在第一页就跳转到当前页
                                        setTimeout(function () {
                                            $('.list_page_box .pagNum').eq(that.curPageIndex).trigger('click')
                                        }, 200)
                                    }
                                } else {
                                    layer.msg(data.msg);
                                }
                            }
                        });
                    },
                    editOrPreview: function (type,id) {
                        var that = this;
                        //翻页列表中元素绑定不了vue click事件,应为绑定的时候dom还没有渲染出来--->在列表渲染之后初始化vue解决,,但这样会造成一个潜在问题。。vue会在列表多次渲染的多次初始化
                        $('body').on('click', '.js_editOrPreview', function () {
                            that.IsShow = false;

                            var id = $(this).data('id');
                            var type = $(this).data('type');
                            var params = {
                                id: id
                            }
                            if (type == 'edit') {
                                that.currentEditId = params.id;
                            } else if (type == 'preview') {
                                that.currentPreviewId = id;
                            }
                            
                            $.ajax({
                                url: '/Agent/GetAgentInfo',
                                type: 'post',
                                data: params,
                                datatype: 'json',
                                success: function (data) {
                                    that.IsShow = false; //显示修改界面
                                    that.initAddOrEdit();
                                    that.setFormValue(data)
                                    that.currentPreviewId && that.disablePreviewForm();
                                    
                                    window.parent.postMessage("dataLoadSuccess", '*');
                                    that.curPageIndex = $('.list_page_box .pagNum.active').index() - 3; //list_page_box的第3个元素才是pagNum第一个1个
                                }
                            });
                        });
                    },
                    disablePreviewForm: function () {
                        $('#panelContent,#covDatgeWrap').addClass('disabled');
                        $("select").prop("disabled", true);
                        $('.js_clone_delect').remove();
                        //禁用selectPage.js创建的下拉,使用延时的原因是创建下拉需要一定的时间,等他创建完成再去修改
                        setTimeout(function () {
                            $('#ParentAgentName_form').selectPageDisabled(true);
                            $('#ParentAgentName_form').closest('.sp_container').removeClass('sp_disabled');
                        }, 500)
                    },
                    initDomEvent: function () {
                        var that = this;
                        $('body').on('change', '#IsHaveParent', function () {
                            that.isHaveParent = $(this).val();
                        });
                        $('body').on('change', '#IsRebate_form', function () {
                            that.isRebate = $(this).val();
                        });
                    },
                    backBtn: function () {
                        this.IsShow = true; //返回列表
                        $('.js_clonejspanel').remove();
                        $('#panelContent,#covDatgeWrap').removeClass('disabled');

                        $("select").prop("disabled", false)
                        $('#ParentAgentName_form').selectPageDisabled(false);

                        this.currentPreviewId = null;
                        this.currentEditId = null;
                        window.parent.postMessage("dataLoadSuccess", '*');
                    },
                    goToadd: function (type) {
                        this.IsShow = false; //显示新增界面
                        this.initAddOrEdit();
                        //清空表单
                        this.clearForm()
                        this.currentEditId = null;
                        window.parent.postMessage("dataLoadSuccess", '*');

                        if (!CustomerNameSelectPage) {//避免重复创建
                            this.getSelectBoxData(function (data) {
                                CustomerNameSelectPage = $('#ParentAgentName_form').selectPage({
                                    showField: 'Name',
                                    keyField: 'ID',
                                    pagination: false,
                                    maxSelectLimit: 10, //限制最多选择个数
                                    data: data
                                });
                            })
                        }
                    },
                    initAddOrEdit: function () { //元素显示后再去创建第三方插件调用
                        $('.ChoiceTime').datetimepicker({
                            format: 'yyyy-mm-dd',
                            weekStart: 1,
                            todayBtn: 1,
                            autoclose: true,
                            todayHighlight: 1,
                            startView: 2,
                            minView: 2,
                            forceParse: 0,
                        });
                    },
                    clearForm: function () {
                        $('#AgentName_form').val('');
                        $('#IsHaveParent').val('1');
                        //$('#ParentAgentName_form').val('');
                        $('#ParentAgentName_form').selectPageClear();
                        $('#IsRebate_form').val('1');
                        $('#RebateDate').val('');
                        this.isHaveParent = 1;
                        this.isRebate = 1;

                        $('.jspanel').find('input').val('');
                    },
                    setFormValue: function (value) {
                        if (!CustomerNameSelectPage) {//避免重复创建
                            this.getSelectBoxData(function (data) {
                                CustomerNameSelectPage = $('#ParentAgentName_form').selectPage({
                                    showField: 'Name',
                                    keyField: 'ID',
                                    pagination: false,
                                    maxSelectLimit: 10, //限制最多选择个数
                                    data: data
                                });
                            })
                        }
                        $('#AgentName_form').val(value.AgentName);
                        $('#IsHaveParent').val(value.IsHaveParent);
                        $('#ParentAgentName_form').val(value.ParentID);
                        $('#ParentAgentName_form').selectPageRefresh(); //设置val后需要刷新列表

                        $('#IsRebate_form').val(value.IsRebate);
                        $('#RebateDate').val(value.RebateDate);

                        this.isHaveParent = value.IsHaveParent;
                        this.isRebate = value.IsRebate;
                        //遍历创建n个、
                        // 。。
                        var dataLen = value.Data.length;
                        while (dataLen > 1) {
                            createContactList();
                            dataLen--;
                        }
                        if (dataLen >= 1) {

                            $.each(value.Data, function (i, item) {
                                $.each(item, function (key, iitem) { // key
                                    $('body').find('.jspanel').eq(i).find('.' + key).val(iitem)
                                });
                            });
                        }
                        //fixed ui style
                        $('#ParentAgentName_form').siblings('label').css({ 'top': '7px', 'font-size': '14px' });
                    },
                    getSelectBoxData: function (cb) {
                        $.ajax({
                            url: '/CustomerBillManage/GetAgent',
                            datatype: 'json',
                            type: "post",
                            success: function (data) {
                                cb && cb(data);
                            }
                        });
                    },
                },
                filters: {
                    formateProductType: function (val) {

                        if (val == 1) {
                            val = '30天产品';
                        } else if (val == 2) {
                            val = '45天产品';
                        } else if (val == 3) {
                            val = '60天产品';
                        }
                        return val
                    }
                }
            });
      //  }
        
    </script>
</body>
</html>
View Code

 

注意我们最后的页面是使用jQuery与vue混合的,其中翻页部分是使用jQuery插件渲染的,其他部分是使用vue+jQuery的

思路

直接当前页面中引入vue.js script标签,通过对右侧节点`#myMenu`创建一个 Vue 实例,直接把当前页面当做template

- 方案1.非component组件化

直接页面内使用

var vm = new Vue({

el: '#myMenu',

data: {

IsShow: true,

},

created: function () {

console.log('xx');

},

methods: {}

})

 

- 方案2.component组件化

新建一个test.js文件,然后当前页面引入这个test.js文件,当做组件注册到页面中去使用

Vue.component('my-test', {

template: '<div> test HTML 代码 {{mgs}}{{title}}</div>',

props: {

title: { default: 'xxx' }

},

data: function () {

return {

mgs: 'testttt'

}

},

created: function () {

console.log(this.mgs);

},

methods: {}

// ...

})

 

posted @ 2019-07-19 10:56  若强  Views(4496)  Comments(1Edit  收藏