Vue基础-双向绑定:从 html 到 模板 到 渲染函数

Vue 测试版本:Vue.js v2.5.13

在 Vue 中,可以利用 v-model 语法糖实现数据的双向绑定,例如:

<div id="app">
     <input 
     type="text" 
     v-model="id" 
     placeholder="please enter your id"
     />
     <p>your id is:  {{ id | formatId }}</p>
</div>
window.onload = function() {    
    Vue.filter('formatId', function(v) {
        return v.length < 10 && v.length > 0 ? v.padStart(10, '0') : v;
    });

    new Vue({
        el: '#app',
        data: {
            id: ''
        }

    });
};

但是有时,我们可能希望用 模板 实现,那么情况就是这样:

<div id="app">
     <my-ele :id="id"></my-ele>
</div>
window.onload = function() {
    Vue.component('my-ele', {
        template: `
        <div>
          <input type="text" v-model="id"/>
          <p>you id:  {{id | formatId}}</p>
        </div>
        `,
        props: ['id']
    });

    Vue.filter('formatId', function(v) {
        return v.length < 10 && v.length > 0 ? v.padStart(10, '0') : v;
    });

    new Vue({
        el: '#app',
        data: {
            id: ''
        }

    });
};

目前为止,都是比较简单的,问题就在于,有时,我们还需要用 render() 函数来实现:

<div id="app">
       <my-ele
        :val-par="id"
        @input-par="id=arguments[0]"
       ></my-ele>
</div>
window.onload = function() {
    Vue.component('my-ele', {
        render(createElement) {
            let self = this;
            let input = createElement('input', {                
                domProps: {
                    type: 'text',
                    placeholder:'please enter your id',
                    value: this.valPar,
                },
                on: {
                    input(e) {
                        self.$emit('input-par', e.target.value);
                    }
                }
            });
            let p = createElement('p', {
                props: {
                    id: this.valPar
                }
            }, 'your id is: '+this.formatId(this.valPar));
            return createElement('div', [input, p]);
        },
        props: ['valPar'],
        methods: {
            formatId(v) {
                return v.length < 10 && v.length > 0 ? v.padStart(10, '0') : v;
            }
        }
    });

    new Vue({
        el: '#app',
        data: {
            id: ''
        }
    });
};

主要注意两点:

  1. value 的双向绑定在设置在 domProps 而不是 props
  2. 过滤器自己实现了个,并不能用 Vue.filter

参考文档:

https://cn.vuejs.org/v2/guide/render-function.html#深入-data-对象

原文地址:https://www.cnblogs.com/xianshenglu/p/8485789.html