初用vue遇到的一些问题

1.过滤器:

 filters: {
        search(list) {         es5
            var _self = this;
            //return list.filter(menu => menu.childs.name.join("").indexOf(this.searchVal) > -1);
            return list.filter(function(menu) {
                var lists = menu.childs;
                var arr = [];
                arr.push(menu.name)
                for (var i = 0, len = lists.length; i < len; i++) {
                    arr.push(lists[i].name);
                }
 
                return arr.join("").indexOf(_self.searchVal) > -1;
            })
        },
        searchlist(list) {              es6
            return list.filter(menulist => menulist.name.indexOf(this.searchVal) > -1);
        }
    },

  

2.ajax:

方法一:在写ready里面

 ready: function() {
        var _self = this;
        $.ajax({
            url: 'url',
            dataType: 'json',
            success: function(data) {
                _self.menus = data.data.menu.childs;
                _self.user = data.data.user;
            },
            error: function(err) {
                console.log(err);
            }
        })
    },

  

3.用路由的时候又要传数据(但是router.start和new Vue不能同时写)

router.start({
    data() {
        return {
            currentmenu: '',
            message: 'asdaaa',
            menus: [],
            user: {},
            searchVal: ''
        }
    },
    filters: {
        search(list) {
            var _self = this;
            //return list.filter(menu => menu.childs.name.join("").indexOf(this.searchVal) > -1);
            return list.filter(function(menu) {
                var lists = menu.childs;
                var arr = [];
                arr.push(menu.name)
                for (var i = 0, len = lists.length; i < len; i++) {
                    arr.push(lists[i].name);
                }
 
                return arr.join("").indexOf(_self.searchVal) > -1;
            })
        },
        searchlist(list) {
            return list.filter(menulist => menulist.name.indexOf(this.searchVal) > -1);
        }
    },
    ready: function() {
        var _self = this;
        // console.log(env.api)
        $.ajax({
            url: 'url',
            dataType: 'json',
            success: function(data) {
                // console.log(data.data.menu.childs);
                // console.log(data.data.user);
                _self.menus = data.data.menu.childs;
                _self.user = data.data.user;
            },
            error: function(err) {
                console.log(err);
            }
        })
    },
    methods: {
        changeCurrent: function(curl) {
            // alert(this.message)
            this.currentmenu = curl;
        }
    },
    component: app
}, "#app");

  

4.文件上传

$.ajaxFileUpload({
                    url: 'url',
                    type: 'post',
                    secureuri: false, //是否启用安全提交,默认为false
                    fileElementId: 'imeiExcelUrl', //文件选择框的id属性
                    dataType: 'json', //返回数据的类型
                    success: function(data) { //服务器响应成功时的处理函数
                        config.data.show = false;
                        if (data.meta.code == '200') {
                            window.location.reload();
                        } 
                        console.log(data.meta);
                    },
                    error: function(data) { //服务器响应失败时的处理函数
                        console.log(data);
                    }
                });

  

5.用v-if指令后,对该dom绑定事件不起作用

换了v-show

6.有没有可以监听地址栏变化的方法

还没解决

7.复制文字到剪切板

(1)
<!-- 点击复制begin -->
 <script type="text/javascript" src="/js/zclip/jquery.zclip.js"></script>
<!-- 点击复制end -->
(2)
$("#phone_number").zclip({
                        path: "/js/zclip/ZeroClipboard.swf",
                        copy: function(){
                        return $(this).val();
                        },
                        beforeCopy:function(){/* 按住鼠标时的操作 */
                            $(this).css("color","orange");
                        },
                        afterCopy:function(){/* 复制成功后的操作 */
                            var $copysuc = $("<div class='copy-tips'><div class='copy-tips-wrap'>☺ 复制成功</div></div>");
                            $("body").find(".copy-tips").remove().end().append($copysuc);
                            $(".copy-tips").fadeOut(3000);
                        }
                    });

  

8.文件上传绑定的onchange事件,用的ajaxfileupload.js 但是change事件第二次失效。

用juqery.upload.js解决了。

$('#img').fileupload({
              add: function(e, data) {
                var uploadErrors = [];
                var acceptFileTypes =  /^image\/(gif|jpe?g|png)$/i;
                if (data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
                    uploadErrors.push('传入的格式不对');
                }
                if (data.originalFiles[0]['size'].length && data.originalFiles[0]['size'] > 5000000) {
                    uploadErrors.push('所选图片太大');
                }
                if (uploadErrors.length > 0) {
                    alert(uploadErrors.join("\n"));
                } else {
                    data.submit();
                }
             },
             url: env.api + "liveman/panorama/panora/cover",
             dataType: 'json',
             autoUpload: true,
             //成功
             done: function(e, data) {
                _self.flagImg = true;
                _self.dataObject.coverUrl = data.result.data;
             },
             //失败
             fail: function(e, data) {
               console.log(data);
             }
          });

  

9.form表单的提交不跳转

html:

<form method="post" name="testForm"  >
          <label for="video_file" class="labelText col-sm-4 text-right">视       频</label>
          <div class="col-sm-2">
              <input type="file" >
          </div>
          <div class="col-sm-1">
              <button type="submit" class="submit" >提交</button>
          </div>
        </form>

  

js:

 $("#showDataForm").on('submit',function(event) {
            $("#showDataForm").ajaxSubmit(function(message) {
                // 提交表单的返回值
                // console.log(message);
                if(message.code == 0) {
                  alert("视频上传成功");
                }else {
                  alert('视频上传失败');
                }
            });
            return false; // 必须返回false,否则表单会自己再做一次提交操作,并且页面跳转
          });

  

10.XMLHttpRequest上传文件做进度条

//进度条函数
function videoUploadProgress(evt) {
              if (evt.lengthComputable) {
                var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                _self.progressBar = percentComplete;
              }
              else {
                console.log(".......")
              }
          }
                    //文件上传成功函数
          function videoUploadComplete(evt) {
            var response = JSON.parse(evt.currentTarget.response);
            if(response.code == 0){
              _self.flagVideo = true;
              alert("视频上传成功");
            }
          }
          //文件上传函数
          function uploadVideo(url) {
              var xhr = new XMLHttpRequest();
              var fd = new FormData();
              fd.append("show_form", document.getElementById('video_file').files[0]);
              xhr.upload.addEventListener("progress", function(){videoUploadProgress(event)}, false);
              xhr.addEventListener("load", videoUploadComplete, false);
              xhr.open("POST", url);
              console.log(url);
              xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
              xhr.send(fd);
          }
          $("#submit").on('click',function(){
            uploadVideo(_self.url);
          });

  

11.绑定图片

<img v-bind:src="item.image">

12.绑定value到Vue实例的一个动态属性上

对于单选按钮,勾选框及选择框选项,v-model绑定的value通常是静态字符串(对于勾选框是逻辑值):

13.vue页面闪烁问题{{message}}

样式:

[v-cloak]{
display:none;
}

dom:

<div v-cloak>{{message}}</div>

  

14.vuejs中过渡动画

样式:

.staggered-transition {
        transition: all .5s ease;
        /*overflow: hidden;*/
        margin: 0;
    }
 
    .staggered-enter,
    .staggered-leave {
        opacity: 0;
    }

dom:

<li class=" treeview" v-for="menu in menus |search" v-bind:class="{'active': searchVal!=''||$index == activeMemuIndex}" transition="staggered" stagger="100">

  

15.局部样式

<style scoped></style>

  支持sass

<style scoped ></style> 

16.webpack区分测试环境、开发环境和正式环境

package.json:

"scripts": {
    "start": "webpack-dev-server --inline",
    "test": "webpack",
    "build": "webpack"
  },

  

webpack.config.js:

if (TARGET === 'start') {
    module.exports.plugins = [
        new webpack.DefinePlugin({
            'env': {
                api: '"kkk"'         测试环境
            }
        }),
        new TransferWebpackPlugin([
            { from: 'exter' }
        ], path.resolve(__dirname, "src")),
        new TransferWebpackPlugin([
            { from: 'login' }
        ], path.resolve(__dirname, "src"))
    ]
    module.exports.devtool = '#source-map'
 
} else {
    module.exports.plugins = [
        new webpack.DefinePlugin({
            'env': {
                api: '"kkk"'      发布环境
            }
        }),
        new TransferWebpackPlugin([             文件拷贝
            { from: 'exter' }
        ], path.resolve(__dirname, "src")),
        new TransferWebpackPlugin([
            { from: 'login' }
        ], path.resolve(__dirname, "src"))
    ]
    module.exports.devtool = '#source-map'
}

  

17.window.open()新窗口

window.location=当前窗口

18.公用模态框组件(父子组件通信)

export default  {
        props: {
            modal: {
                title: '',
                content: '',
                flag: '',
                id: '',
                show: false,
                num: ''
            },
            focusList: []
        },
          methods: {
            refresh: function() {
                this.deleteFocusSure();
            },
            deleteFocusSure: function(id) {//确定删除
                var _self = this;
                $.ajax({
                    url: 'url',
                    data: {id: _self.modal.id},
                    success: function(data) {
                        if(data.meta.code == 200) {
                            for (let i = 0; i < _self.focusList.length; i++) {
                                if(_self.focusList[i].id == _self.modal.id) {
                                    _self.focusList.splice(i,1);
                                    _self.modal.show = false;
                                    _self.$dispatch('focusList', _self.focusList); //通知
                                }
                            }
                        }
                    },
                    err: function(err) {
                        console.log(err);
                    }
                });
            },
           
        },
        events: { //通知
            'refresh' () {
                this.refresh();
            }
        },
}
 

  

html:

<modal-file :modal="modal" :focus-list="focusList"></modal-file>

  

js:

import modalFile from './modalFile.vue';
export default {
        data() {
            return {
                focusList: [],
                modal: {}
            }
        },
         components: {
           modalFile
        },
        methods: {
            deleteFocus: function(id) {//删除
                this.modal = {
                    show: true,
                    title: '删除',
                    content: '确定删除该数据?',
                    flag: 1,
                    id: id
                }
            },
            Preview: function(data,type,userid) {//预览
                var _self = this;
                if(type == 3 ) {
                    $.ajax({
                        url: 'ur',
                        data: {liveid:data,type:3},
                        success: function(data) {
                            var activityId = data.data;
                            _self.modal = {
                              show: true,
                              title: "直播预览",
                              flag: 2,
                              id: activityId,
                            }
                        }
                    }); 
               }
              }     
        },
events: { //刷新
                // 分页组件传回的表格数据(这里即为服务器传回的数据)
                'data' (data) {
                    this.focusList = data.data.data;
                    console.log(this.focusList);
                },
                'focusList' (focusList) {//删除后的刷新
                    this.focusList = focusList;
                }
            }
}

  

19.watch的使用

watch: {
             'selectedType': 'getPlaceholder'
        }

'selectedType':是data里面定义的变量;

'getPlaceholder':是methods里面定义的方法

20.vue的分页组件 pageBage.vue

<!-- 表格分页组件 -->
<template>
    <nav class="boot-nav">
        <ul class="pagination boot-page">
            <li>
                <a href="javascript:void(0)"  @click="wholePrevClick()">
                    <span aria-hidden="true">第一页</span>
                </a>
            </li>
            <li>
                <a href="javascript:void(0)" aria-label="Previous" @click="onPrevClick()">
                    <span aria-hidden="true">«</span>
                </a>
            </li>
            <li v-for="page in pages" :class="activeNum === $index ? 'active' : ''">
                <a href="javascript:void(0)" v-text="page" @click="onPageClick($index)"></a>
            </li>
            <li>
                <a href="javascript:void(0)" aria-label="Next" @click="onNextClick()">
                    <span aria-hidden="true">»</span>
                </a>
            </li>
            <li>
                <a href="javascript:void(0)"  @click="wholeNextClick()">
                    <span aria-hidden="true">最后一页</span>
                </a>
            </li>
        </ul>
        <div class="page-total">
            共 <span v-text="pageTotal"></span> 页
        </div>
    </nav>
</template>

<script>
export default {
    props: {
        // 页码
        pages: {
            type: Array,
            default: function () {
                return [1]
            }
        },
        // 每页显示个数
        len: {
            type: Number,
            default: 10
        },
        // 表格数据(数组)
        data: {
            type: Array,
            default: function () {
                return []
            }
        },
        // AJAX地址
        url: {
            type: String,
            default: ''
        },
        //当前页的字段
        currentPage: {
            type: String,
            default: ''
        },
        totalPages: {
            type: String,
            default: ''
        },
        totalName: {
            type: String,
            default: ''
        },
        // 显示页数
        pageLen: {
            type: Number,
            default: 10
        },
        // 总页数
        pageTotal: {
            type: Number,
            default: 1
        },
        // 参数内容
        param: {
            type: Object,
            default: function () {
                return {}
            }
        },
        //method
        method:{
            type:String,
            default:'get'
        }
    },
    data () {
        return {
            activeNum: 0,
            first: -1,
            last: -1
        }
    },
    methods: {
        // 第一页
        wholePrevClick: function() {
            this.first = 1;
            var newPages = [];
            for (let i = 0; i < this.pages.length; i++) {
                newPages[i] = i +1;
            }
            this.pages = newPages;
            this.activeNum = 0;
            this.getData();
        },
        // 最后一页
        wholeNextClick: function() {
            this.last = this.pageTotal;
            var newPages = [];
            for (let i = 0; i < this.pages.length; i++) {
                newPages[this.pages.length-i-1] = this.pageTotal-i;
            }
            this.pages = newPages;
            this.activeNum = this.pages.length-1;
            this.getData();
        },
        pageMake: function(index) {
            let newPages = [];
            let len2 = parseInt(this.pages.length/2);
            if(this.pages[index] <= len2 || this.pageTotal <= this.pageLen || this.pages[index] > this.pageTotal-len2) {
                for (let i = 0; i < this.pages.length; i++) {
                    newPages[i] = this.pages[i];
                }
                this.activeNum = index;
            }else if( this.pages[index] <= this.pageTotal-len2) {
                for (let i = 0; i < this.pages.length; i++) {
                    newPages[i] = this.pages[index]-len2+i;
                }
                this.activeNum = len2;
            }
            this.pages = newPages;
            this.getData();
        },
        // 点击页码刷新数据
        onPageClick (index) {
            this.pageMake(index);
        },
        // 上一页
        onPrevClick () {
            // 当前页是否为当前最小页码
            if (this.activeNum > 0) {
                // this.activeNum = this.activeNum - 1;
                let index = this.activeNum -1;
                this.pageMake(index);
            } else {
                if (this.pages[0] !== 1) {
                    let newPages = []
                    for (let i = 0; i < this.pages.length; i++) {
                        newPages[i] = this.pages[i] - 1
                    }
                    this.pages = newPages
                    this.getData()
                }
            }
        },
        // 下一页
        onNextClick () {
            // 当前页是否为当前最大页码
            if (this.activeNum < this.pages.length - 1) {
                // this.activeNum = this.activeNum + 1
                let index = this.activeNum + 1;
                this.pageMake(index);
            } else {
                if (this.pages[this.pages.length - 1] < this.pageTotal) {
                    let newPages = []

                    for (let i = 0; i < this.pages.length; i++) {
                        newPages[i] = this.pages[i] + 1
                    }
                    this.pages = newPages
                    this.getData()
                }
            }
        },
        // 获取页码
        getPages () {
            this.pages = []
            // 比较总页码和显示页数
            if (this.pageTotal <= this.pageLen) {
                //console.log(this.pageTotal+"....."+this.pageLen)
                for (let i = 1; i <= this.pageTotal; i++) {
                    this.pages.push(i)
                }
            } else {
                for (let i = 1; i <= this.pageLen; i++) {
                    this.pages.push(i)
                }
            }
        },
        // 页码变化获取数据
        getData () {
            var _self = this;
            this.param[_self.currentPage] = this.pages[_self.activeNum];
            this.param.rows = this.len;
            if( this.first!= -1) {
                this.param[_self.currentPage] = this.first;
                this.first = -1;
            }else if (this.last != -1) {
                this.param[_self.currentPage] = this.last;
                this.last = -1;
            }
            $.ajax({
                 url: this.url,
                 method: this.method,
                 data: this.param,
                 dataType: 'json',
                 success: function(data) {
                    if(_self.totalName) {
                         _self.pageTotal = Math.ceil(data.data[_self.totalName][_self.totalPages]/ _self.len);
                    }else {
                         _self.pageTotal = Math.ceil(data.data[_self.totalPages]/ _self.len);
                    }

                    if (_self.pages.length !== _self.pageLen || _self.pageTotal < _self.pageLen) {
                        _self.getPages();
                    }
                    _self.$dispatch('data', data)
                 },
                 error: function(err) {
                    // console.log(err);
                 }
            });
        },
        refresh () {
            this.pages = [1]

            this.activeNum = 0

            this.getData()
        }
    },
    ready () {
          this.getData();
          this.getPages();
    },
    events: {
        'refresh' () {
            this.refresh();
        }
    }
}

</script>

<style scoped>
.boot-select {
    float: left;
    width: 80px;
}

.boot-nav {
    float: right;
}

.boot-page {
    display: inline-block;
    margin: 2px 10px 0 20px;
    vertical-align: middle;
}

.page-total {
    display: inline-block;
    vertical-align: middle;
}
</style>

  

21.watch

定义了一个对象类型的数据(例如:obj),改变了属性(例如:obj.name),触发不了watch事件。

22.img

dom:

  < img :src="img"/>

  

js:

data() {
         return {
              img: require('../../login/login/imgs/progress.gif') 
          } 
     }

  

23.vue-resource:http://www.doc00.com/doc/1001004eg

24.子组件的索引:

1. 直接用$children索引,

this.$children[index]

2. 为组件添加索引ID后通过id获取:

template:
<live-player v-ref:liverplayer :live-title="liveTitle" :live-src="liveSrc"></live-player>
script:
this.$refs.liverplayer

  注意:如果v-ref:liverplayerM再用this.$refs.liverplayerM会取不到值(因为用了驼峰法吧)。

25.设置了disabled的a标签置灰但是@click的点击仍然可用