您现在的位置:首页 >> 前端 >> 内容

讲述vue.js里一个与赋值响应相关的坑

时间:2018/5/11 14:31:51 点击:

  核心提示:双向绑定相关先说需求。需求是这样的:{1、实现一个输入框2、在输入框里面输入并且并且输入enter就会框下面出现出现相应字符,可叠增3、相应字符后面有一个按钮,按下就会使此行销毁4、在最后有一个按钮,...

双向绑定相关

    先说需求。

    需求是这样的:

    1、实现一个输入框

    2、在输入框里面输入并且并且输入enter就会框下面出现出现相应字符,可叠增

    3、相应字符后面有一个按钮,按下就会使此行销毁

    4、在最后有一个按钮,点击会销毁全部行

    实现是这样的:

    直接上代码啦!

html:{

        

<p class="content">

    <input v-model="newLine" v-on:keyup.enter="addLine">

    <ul>

        <li v-for="line in table">

            <span>{{ line.text }}__{{line.index}}</span>

            <button v-on:click="removeLine(line.index)">X</button>

        </li>

        <button v-on:click="removeAll">removeAll</button>

    </ul>

</p>

</body>

<script type="text/javascript" src="load.js"></script>

    }

js:{

load.js

try {

    var sourceArr = [

        "../js/vue.js",

    ]

    sourceArr.forEach(function (source) {

        document.write("<script language=javascript src="+source+"></script>");

    })

}catch (e){

}

var tableValue = [];

new Vue({

    el: '.content',

    data: {

        newLine: '',

        table: tableValue

    },

    methods: {

        addLine: function () {

            var text = this.newLine;

            console.log(text)

            if (text) {

                this.table.push({text: text, index: this.table.length});

                this.newLine = '';

            }

        },

        removeLine: function (index) {

            var j = 0;

            this.table.forEach(function (line) {

                if (line["index"] == index) {

                    tableValue.splice(j, 1);

                }

                j++;

            });

        },

        removeAll: function () {

            var type = 1;

            if(type){

                //解决方法1

                while(tableValue.length != 0){

                    tableValue.splice(0,1);

                }

            }else {

                //解决方法2

                tableValue = [];

                this.table = tableValue;

            }

        }

    }

});

    }

这里有一个地方有趣的是:

注意这里的解决方法二,如果在tableValue里面赋空之后不将this.table赋空值的话,就不会触发this.table和tableValue的动态响应,把tableValue对象操作使用就没有这样的现象。

看到这里你猜到什么了吗?

刚看vue,eee,同时是js小白,希望各位能够多多的批评我的代码,因为我自己都看不下去啦!为了达到功能无恶不作,(逃)。

望斧正。

Tags:讲述 述V VU UE 
作者:网络 来源:qq_3678218