vue.js 使用jsx语法

在项目目录下安装

npm install babel-plugin-syntax-jsx
npm install babel-plugin-transform-vue-jsx
npm install babel-helper-vue-jsx-merge-props
npm install babel-preset-es2015

执行后,项目目录下会生成一个.babelrc文件,修改文件,如果有其他的内容要合并

{
  "presets": ["es2015"],
  "plugins": ["transform-vue-jsx"]
}

参考:https://github.com/vuejs/babel-plugin-transform-vue-jsx#usage

vue在jsx语法中定义的事件,阻止冒泡

使用了element的属性结构,在后面添加了“修改”“删除”功能,点击这两个按钮时,阻止冒泡,禁止父元素展开和折叠

 <div class="form-box">
            <el-tree :data="data" :props="defaultProps"  node-key="id"  :render-content="renderContent" ></el-tree>
        </div>
 renderContent(h, { node, data, store }) {

                return (
                    <span >

                          <span >
                                <span>{node.label}</span>
                          </span>
                          <span style="margin-left:200px;">
                                <el-button size="small" icon="edit" class="warning-btn"  on-click={ ()=>this.handleNodeClick(store,data)}>修改</el-button>
                                <el-button size="small" icon="delete" class="danger-btn" on-click={ ()=>this.remove(store,data)}>删除</el-button>
                          </span>
                    </span>
                );
            },
  handleNodeClick(store,data) {           
                event.cancelBubble = true;               
            },

vue表单

select

 <el-select v-model="form.role" placeholder="请选择">
                        <el-option v-for="item in roles"
                                   :key="item.id"
                                   :label="item.roleName"
                                   :value="item.id"></el-option>

                    </el-select>

注意: 如果key和value属性前面没有加‘:’,则item.id都为最后一个元素的id

密码验证

data: function(){
            var validatePass = (rule, value, callback) => {
                if (value === '') 
                {
                  callback(new Error('请输入密码'));
                } 
                else 
                {
                  if( !/^[a-zA-Z]\w{5,17}$/g.exec(value) )
                  {
                    callback(new Error('密码必须以字母开头,长度在6~18之间,只能包含字母、数字和下划线'));
                  }else{
                     callback();
                  }
                }
            };
            return {
                form: {
                    name: '',
                    pass: ''
                },
                rules: {
                    name: [
                        { required: true, message: '请输入用户名', trigger: 'blur' }
                    ],
                    pass: [
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { min: 3, message: '长度至少6个字符', trigger: 'blur' },
                        { validator: validatePass, trigger: 'blur' }
                    ]
                }
            }
        },

日期格式化

 // 格式化日期
            formatDate( _now ) {
                var now = new Date(_now);
                var year = now.getFullYear();     
                var month = (now.getMonth()+1)>9 ? (now.getMonth()+1) : "0"+(now.getMonth()+1);   
                var date = now.getDate()>9 ? now.getDate() : "0"+now.getDate();     

                var hour = now.getHours()>9 ? now.getHours() : "0"+now.getHours();     
                var minute = now.getMinutes()>9 ? now.getMinutes() : "0"+now.getMinutes();     
                var second = now.getSeconds()>9 ? now.getSeconds() : "0"+now.getSeconds(); 

                return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;     
            },  
            formatter1(row, column) {

                row.createTime = this.formatDate(row.createTime);
                return row.createTime;
            },
            formatter2(row, column) {

                row.lastLoginTime = this.formatDate(row.lastLoginTime);
                return row.lastLoginTime;
            },
            filterTag(value, row) {
                return row.tag === value;
            },

使用 moment 格式化时间

import moment from 'moment';
 <div  class="col-item">{{ dateFormat(item.regTime) }}</div>

 methods里面 
 //时间格式化
          dateFormat:function(date) {
              if (date == undefined || !date) {
                  return "";
              }
              return this.$moment(date).format("YYYY-MM-DD");
          },

tree树节点,添加修改和删除

##html

<el-tree :data="data" :props="defaultProps"  node-key="id" ref="tree" :render-content="renderContent"></el-tree>

    export default {
        data() {
            return {
                data: [],
                defaultProps: {
                    children: 'subs',
                    label: 'title',
                }
            };
        },
        created(){
            this.getData();
        },
        methods: {
            getData(){}, 
            renderContent(h, { node, data, store }) {
                   return (
                    <span >

                          <span >
                                <span>{node.label}</span>
                          </span>
                          <span style="margin-left:200px;">
                                <el-button size="small" icon="edit" class="warning-btn"  on-click={ ()=>this.handleNodeClick(store,data)}>修改</el-button>
                          </span>
                    </span>
                );
            },           
        }
    };

使用拦截器,拦截返回的状态码不在200和300之间的结果

import axios from 'axios';
// http response 拦截器
axios.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        return Promise.reject(error.response.data)   // 返回接口返回的错误信息
    });

//post请求封装
Vue.prototype.$mPost = function(paramObj,okCallback,errorCallback = null,catchCallback=null){ 
var data = JSON.parse(localStorage.getItem('data')); 
    this.$axios.post(this.$global.API_URL,{       
        "param":paramObj.param
    },{
        headers:{'stoken':data.stoken,'sid':data.sid}
    }).then((res) => {
        if(res.data.code == 200 || res.data.result == 200){
            //状态码为200
            okCallback ? okCallback.call(null, res) : function(){}
        }else{
            //状态码>200,小于300
            errorCallback ? errorCallback.call(null,res) : this.$router.push('/login');
        }

    }).catch((ret)=>{
        //状态码不在200300之间的情况
        catchCallback ? catchCallback.call(null, ret) : function(){}
    });
}

在vue中引入外部插件(生成二维码插件为例)

 mounted: function () {
           //钩子函数,等于vue1.0中的ready
            this.$nextTick(function () {
                require ('./../../../static/js/jquery.min.js');
                require ('../../../static/js/jquery.qrcode.min.js');
                this.qrcode();//调用二维码生成函数
            })
        },
     methods: {
            qrcode () {
                $("#code").qrcode({
                    text: this.codeUrl,
                    width:130,
                    height:130
                });
            }        
        }

@command 将多个时间绑定到同一个函数中,通过command区分每个事件

<el-dropdown trigger="click" @command="handleCommand">
                <span class="el-dropdown-link">                    
                    莉莉安
                </span>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="loginout">退出</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
 methods:{
            handleCommand(command) {
                if(command == 'loginout'){                   
                    this.$router.push('/login');
                }
            }
        }
Logo

前往低代码交流专区

更多推荐