实现Vue.js中的双向绑定

v-model的作用

v-model可以实现表单元素和model中元素的双向绑定
注意:v-model只能运用在表单元素中
包括input(radio,text,address,email...) select checkbox textarea

 <div class="app">
        <h4>{{msg}}</h4>
        <!-- v-bind:只能实现数据的单向绑定 -->
       <input type="text" v-bind:value="msg" style="width:100%">

        <!-- 使用v-model可以实现表单元素和model中元素的双向绑定 -->
        <input type="text" v-model="msg" style="width:100%">

    </div>


    <script>
        var vm = new Vue({
            el: '.app',
            data: {
                msg: '热爱学习,学习使我快乐'
            },
            methods: {}
        })
    </script>

使用v-model实现一个简易计算器

<body>
    <div class="app">
        <input type="text" v-model="n1">

        <select v-model="opt">
            <option value="+">+</option>
            <option value="-">-</option>
            <option value="*">*</option>
            <option value="/">/</option>
        </select>

        <input type="text" v-model="n2">

        <input type="button" value="=" @click="calc">

        <input type="text" v-model="result">
    </div>

    <script>
        var vm = new Vue({
            el: '.app',
            data: {
                n1: 0,
                n2: 0,
                result: 0,
                opt: '+'
            },
            methods: {
                calc() {
                    switch (this.opt) {
                        case '+':
                            this.result = parseInt(this.n1) + parseInt(this.n2)
                            break;
                        case '-':
                            this.result = parseInt(this.n1) - parseInt(this.n2)
                            break;
                        case '*':
                            this.result = parseInt(this.n1) * parseInt(this.n2)
                            break;
                        case '/':
                            this.result = parseInt(this.n1) / parseInt(this.n2)
                            break;
                    }
                }
            }
        })
    </script>
</body>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容