实例分析,常用form表单和table列表实现

创建工程test_admin

# 创建工程
vue init webpack test_admin
# 进入工程目录
cd test_admin
# 安装插件
npm install
npm run dev

看到熟悉的页面就表示成功创建工程了

创建基于iview的布局框架

引入iview插件

1、项目安装iview插件

cnpm install iview --save

2、修改src/main.js添加iview的依赖

import iView from 'iview';
import 'iview/dist/styles/iview.css';    // 使用 CSS
Vue.use(iView);

3、添加布局框架
修改src/App.vue为

<template>
    <div class="layout">
        <Row type="flex">
            <Col span="5" class="layout-menu-left">
                <Menu active-name="1-2" theme="dark" width="auto" :open-names="['1']">
                    <div class="layout-logo-left"></div>
                    <Submenu name="1">
                        <template slot="title">
                            <Icon type="ios-navigate"></Icon>
                            导航一
                        </template>
                        <MenuItem name="1-1">选项 1</MenuItem>
                        <MenuItem name="1-2">选项 2</MenuItem>
                        <MenuItem name="1-3">选项 3</MenuItem>
                    </Submenu>
                    <Submenu name="2">
                        <template slot="title">
                            <Icon type="ios-keypad"></Icon>
                            导航二
                        </template>
                        <MenuItem name="2-1">选项 1</MenuItem>
                        <MenuItem name="2-2">选项 2</MenuItem>
                    </Submenu>
                    <Submenu name="3">
                        <template slot="title">
                            <Icon type="ios-analytics"></Icon>
                            导航三
                        </template>
                        <MenuItem name="3-1">选项 1</MenuItem>
                        <MenuItem name="3-2">选项 2</MenuItem>
                    </Submenu>
                </Menu>
            </Col>
            <Col span="19">
                <div class="layout-header"></div>
                <div class="layout-breadcrumb">
                    <Breadcrumb>
                        <BreadcrumbItem href="#">首页</BreadcrumbItem>
                        <BreadcrumbItem href="#">应用中心</BreadcrumbItem>
                        <BreadcrumbItem>某应用</BreadcrumbItem>
                    </Breadcrumb>
                </div>
                <div class="layout-content">
                    <div class="layout-content-main">内容区域</div>
                </div>
                <div class="layout-copy">
                    2011-2016 &copy; TalkingData
                </div>
            </Col>
        </Row>
    </div>
</template>
<script>
    export default {

    }
</script>
<style lang="scss">
  @import "./style/style";
</style>

这里我们用到了Row和Col布局标签,iview把个Row划分为24份,Col中的span确定该区域所占列数;菜单区域和内容区域分别为5列和19列的布局。
同时也使用菜单标签Menu,子菜单Submenu和菜单项MenuItem

新增src/style/style.scss文件

.layout{
    border: 1px solid #d7dde4;
    background: #f5f7f9;
    position: relative;
}
.layout-breadcrumb{
    padding: 10px 15px 0;
}
.layout-content{
    min-height: 480px;
    margin: 15px;
    overflow: hidden;
    background: #fff;
    border-radius: 4px;
}
.layout-content-main{
    padding: 10px;
}
.layout-copy{
    text-align: center;
    padding: 10px 0 20px;
    color: #9ea7b4;
}
.layout-menu-left{
    background: #464c5b;
}
.layout-header{
    height: 60px;
    background: #fff;
    box-shadow: 0 1px 1px rgba(0,0,0,.1);
}
.layout-logo-left{
    width: 90%;
    height: 30px;
    background: #5b6270;
    border-radius: 3px;
    margin: 15px auto;
}

运行前添加依赖的插件

cnpm install sass-loader --save
cnpm install node-sass --save

执行运行命令:cnpm run dev
页面如下:
6

添加form表单和table列表页

1、创建src/page/form.vue和src/page/table.vue
内容分别为:

<template>
  <div>
    this is form page!
  </div>
</template>
<script>
export default {
}
</script>
<template>
  <div>
    this is table page!
  </div>
</template>
<script>
export default {
}
</script>

2、配置路由,修改src/router/index.js内容为

import Vue from 'vue'
import Router from 'vue-router'
import FormPage from '@/page/form'
import TablePage from '@/page/table'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/form',
      name: 'form',
      component: FormPage
    },
    {
      path: '/table',
      name: 'table',
      component: TablePage
    }
  ]
})

3、主页添加路由
修改菜单,menu添加on-select属性,修改menu-item的name属性为router中的name名称,并修改对应的显示值

<Menu active-name="1-2" theme="dark" width="auto" :open-names="['1']" @on-select="openView">
    <div class="layout-logo-left"></div>
    <Submenu name="1">
        <template slot="title">
            <Icon type="ios-navigate"></Icon>
            示例
        </template>
        <MenuItem name="form">
            form表单示例
        </MenuItem>
        <MenuItem name="table">
            table表格示例
        </MenuItem>
        <MenuItem name="1-3">选项 3</MenuItem>
    </Submenu>
    <Submenu name="2">
        <template slot="title">
            <Icon type="ios-keypad"></Icon>
            导航二
        </template>
        <MenuItem name="2-1">选项 1</MenuItem>
        <MenuItem name="2-2">选项 2</MenuItem>
    </Submenu>
    <Submenu name="3">
        <template slot="title">
            <Icon type="ios-analytics"></Icon>
            导航三
        </template>
        <MenuItem name="3-1">选项 1</MenuItem>
        <MenuItem name="3-2">选项 2</MenuItem>
    </Submenu>
</Menu>

src/App.vue注册openView方法

添加菜单链接显示区域,当点击” form表单示例”和”table表格示例”时,页面会在router-view标签区域显示

实现常用form表单功能

form内容显示

修改form.vue文件内容为:

<template>
    <div class="layout-content">
        <div class="layout-content-main">
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100">
                <FormItem label="姓名" prop="name" >
                    <Input v-model="formValidate.name" placeholder="请输入姓名" class="input-select-class"></Input>
                </FormItem>
                <FormItem label="邮箱" prop="mail">
                    <Input v-model="formValidate.mail" placeholder="请输入邮箱" class="input-select-class"></Input>
                </FormItem>
                <FormItem label="城市" prop="city">
                    <Select v-model="formValidate.city" placeholder="请选择所在地" class="input-select-class">
                        <Option value="beijing">北京市</Option>
                        <Option value="shanghai">上海市</Option>
                        <Option value="shenzhen">深圳市</Option>
                    </Select>
                </FormItem>
                <FormItem label="选择日期">
                    <Row>
                        <Col span="3">
                            <FormItem prop="date">
                                <DatePicker type="date" placeholder="选择日期" v-model="formValidate.date"></DatePicker>
                            </FormItem>
                        </Col>
                        <Col span="1" style="text-align: center">-</Col>
                        <Col span="3">
                            <FormItem prop="time">
                                <TimePicker type="time" placeholder="选择时间" v-model="formValidate.time"></TimePicker>
                            </FormItem>
                        </Col>
                    </Row>
                </FormItem>
<FormItem label="选择日期时间">
                    <Row>
                        <Col span="3">
                            <FormItem prop="datetime">
                                <DatePicker type="datetime" placeholder="选择日期时间" v-model="formValidate.date"></DatePicker>
                            </FormItem>
                        </Col>
                    </Row>
                </FormItem>
                <FormItem label="性别" prop="gender">
                    <RadioGroup v-model="formValidate.gender">
                        <Radio label="male"></Radio>
                        <Radio label="female"></Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="爱好" prop="interest">
                    <CheckboxGroup v-model="formValidate.interest">
                        <Checkbox label="吃饭"></Checkbox>
                        <Checkbox label="睡觉"></Checkbox>
                        <Checkbox label="跑步"></Checkbox>
                        <Checkbox label="看电影"></Checkbox>
                    </CheckboxGroup>
                </FormItem>
                <FormItem label="介绍" prop="desc">
                    <Input v-model="formValidate.desc" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入..." class="input-select-width-middle-class"></Input>
                </FormItem>
                <FormItem>
                    <Button type="primary" @click="handleSubmit('formValidate')">提交</Button>
                    <Button type="ghost" @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button>
                </FormItem>
            </Form>
        </div>
    </div>
</template>

<script>
    export default {
      data () {
        return {
          formValidate: {
            name: '',
            mail: '',
            city: '',
            gender: '',
            interest: [],
            date: '',
            time: '',
            datetime: '',
            desc: ''
          },
          ruleValidate: {
            name: [
              { required: true, message: '姓名不能为空', trigger: 'blur' }
            ],
            mail: [
              { required: true, message: '邮箱不能为空', trigger: 'blur' },
              { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
            ],
            city: [
              { required: true, message: '请选择城市', trigger: 'change' }
            ],
            gender: [
              { required: true, message: '请选择性别', trigger: 'change' }
            ],
            interest: [
              { required: true, type: 'array', min: 1, message: '至少选择一个爱好', trigger: 'change' },
              { type: 'array', max: 2, message: '最多选择两个爱好', trigger: 'change' }
            ],
            date: [
              { required: true, type: 'date', message: '请选择日期', trigger: 'change' }
            ],
            desc: [
              { required: true, message: '请输入个人介绍', trigger: 'blur' },
              { type: 'string', min: 20, message: '介绍不能少于20字', trigger: 'blur' }
            ]
          }
        }
      },
      methods: {
        handleSubmit (name) {
          this.$refs[name].validate((valid) => {
            if (valid) {
              this.$Message.success('提交成功!')
            } else {
              this.$Message.error('表单验证失败!')
            }
          })
        },
        handleReset (name) {
          this.$refs[name].resetFields()
        }
      }
    }
</script>

这里我们使用了Form标签和Form项FormItem,以及常用的输入Input,下拉列表Select,日期选择器DatePicker和时间选择器TimePicker,单选按钮RadioGroup和Radio,多选按钮CheckboxGroup和Checkbox,按钮Button
Form标签具有model属性描述绑定对象,rules属性描述校验规则,label-width属性描述FormItem标签的label的宽度
FormItem具有prop对象Form的model对象的字段,label属性为文字描述
Input,Select,RadioGroup和CheckboxGroup的v-model绑定的具体字段,placeholder输入框中的占位符
DatePicker的type可以选择只有日期的date和包含日期时间的datetime
Button的type确定按钮的类型,@click描述鼠标点击的响应事件
为修饰样式,在src/style/style.scss中添加

.input-select-class {
    width: 200px;
    padding-bottom:5px;
}

.input-select-width-middle-class {
    width: 400px;
}

具体界面如下:
7

实现form表单的ajax提交

目前常用的ajax调用插件是axios
1、引入插件,在项目目录,运行如下命令

cnpm install axios --save

2、为便于开发,封装ajax调用类src/utils/api.js
具体内容如下:

// 配置API接口地址
var root = 'http://sunhaojie.com.test'
// 引用axios
var axios = require('axios')
// 自定义判断元素类型JS
function toType (obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
// 参数过滤函数
function filterNull (o) {
  for (var key in o) {
    if (o[key] === null) {
      delete o[key]
    }
    if (toType(o[key]) === 'string') {
      o[key] = o[key].trim()
    } else if (toType(o[key]) === 'object') {
      o[key] = filterNull(o[key])
    } else if (toType(o[key]) === 'array') {
      o[key] = filterNull(o[key])
    }
  }
  return o
}
/*
 * 接口处理函数
 */
function apiAxios (method, url, params, success, failure) {
  if (params) {
    params = filterNull(params)
  }
  axios({
    method: method,
    url: url,
    data: method === 'POST' || method === 'PUT' ? params : null,
    params: method === 'GET' || method === 'DELETE' ? params : null,
    baseURL: root,
    withCredentials: false
  })
  .then(function (res) {
    if (res.data.status === 200) {
      if (success) {
        success(res.data)
      }
    } else {
      if (failure) {
        failure(res.data)
      } else {
        window.alert('error: ' + JSON.stringify(res.data))
      }
    }
  })
  .catch(function (err) {
    let res = err.response
    if (res) {
      window.alert('api error, HTTP CODE: ' + res.status)
    }
  })
}
// 返回在vue模板中的调用接口
export default {
  get: function (url, params, success, failure) {
    return apiAxios('GET', url, params, success, failure)
  },
  post: function (url, params, success, failure) {
    return apiAxios('POST', url, params, success, failure)
  },
  put: function (url, params, success, failure) {
    return apiAxios('PUT', url, params, success, failure)
  },
  delete: function (url, params, success, failure) {
    return apiAxios('DELETE', url, params, success, failure)
  }
}

在src/main.js中添加关于api.js的引用

import api from './utils/api.js'
Vue.prototype.$api = api

3、提供mock方法
因为是ajax调用,需要有服务器端接口提供服务,这里使用mock.js插件实现服务端端接口的模拟功能
安装mockjs插件

cnpm install mockjs --save

创建src/utils/mock.js文件,并开发如下功能:

import Mock from 'mockjs'
Mock.mock('http://sunhaojie.com.test/api/v1/post', 'post', {
  'status': 200,
  'errorCode': 'SUCCESS',
  'message': '操作成功',
  'timestamp': '2017-10-17 12:12:12',
  'path': '/api/v1/post',
  'method': null,
  'requestId': null,
  'resultData': null,
  'subErrors': null
})

在src/main.js中引入mock.js

import demoMockjs from './utils/mock.js'

4、开发提交form功能
修改src/page/form.vue中handleSubmit方法为

handleSubmit (name) {
  this.$refs[name].validate((valid) => {
    if (valid) {
      this.$Message.success('提交成功!')
    } else {
      this.$Message.error('表单验证失败!')
    }
  })
  var self = this
  self.$api.post('/api/v1/post', self.formItem, function (result) {
    self.$router.push({ path: '/table' })
  })
},

form表单开发完成了,在form提交后页面会跳转到table界面。