vue系列教程:3.vue.js实现可编辑的div

时间:17-03-12 栏目:Javascript, Vue 作者:zongyan86 评论:0 点击: 4,445 次

晒demo代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <style type="text/css">
        .container {
            width: 960px;
            margin: 0 auto;
        }

        .editor {
            margin-right: 360px;
            border: 1px outset black;
            height: 300px;
            padding: 30px;
        }

        .preview {
            padding: 30px;
            float: right;
            width: 300px;
            border: 1px inset grey;
            height: 300px;
        }
    </style>
    <script src="http://cdn.jsdelivr.net/vue/1.0.12/vue.min.js"></script>
</head>
<body>
    <div class='container' id="editor">
        <input type="text" v-model="content" />
        <div class="preview">{{content}}</div>
        <div class='editor' v-divmodel="content" contenteditable="true"></div>
    </div>
    <script type="text/javascript">
    
        Vue.directive('divmodel', { //注意不可写成驼峰的divModel
            twoWay: true,  
            bind: function () {
                this.handler = function () {
                    this.set(this.el.innerHTML)
                }.bind(this)
                this.el.addEventListener('keyup', this.handler)
            },
            update: function (newValue, oldValue) {
                this.el.innerHTML = newValue || ''
            },
            unbind: function () {
                this.el.removeEventListener('keyup', this.handler)
            }
        })

        var vm = new Vue({
            el: '#editor'
        })

    </script>
</body>

</html>

web开发分享



声明: 本文由( zongyan86 )原创编译,转载请保留链接: vue系列教程:3.vue.js实现可编辑的div

关注我们