Vue 组件实现表单的双向绑定

来源:互联网 发布:美中国际 知乎 编辑:程序博客网 时间:2024/05/02 04:46

下面是一个简单的货币输入的自定义控件,来自https://cn.vuejs.org/v2/guide/components.html:

<body><div id="currency-input">    <p>{{price}}</p>    <currency-input v-model="price"></currency-input></div></body><script>    Vue.component('currency-input',{        template: '' +        '<span>' +        '$ <input ref="input" :value="value" @input="updateValue($event.target.value)">' +        '</span>',        props: ['value'],        methods: {            updateValue: function (value) {                //去除空格,保留两位小数                var formattedValue = value.trim().slice(0,value.indexOf('.') === -1 ? value.length : value.indexOf('.')+3);                if(formattedValue !== value){                    this.$refs.input.value = formattedValue;                }                this.$emit('input', Number(formattedValue))            }        }    });    new Vue({        el: "#currency-input",        data: {            price: 0        }    })


关于这段代码,看的时候有一些疑问,把自己的理解记录下来,有可能不准确,以后如果有新的理解再来更新

1、<currency-input v-model="price"></currency-input>v-model是用在<input>中的,组件中为什么要用v-model?

组件 currency-input 实现的是输入框组件,组件也可以依靠 v-model 实现双向绑定。


2、this.$emit('input', Number(formattedValue))有什么作用,为什么改变输入框文字后还要特地用 $emit 触发 input 事件?

这是组件和<input>不同的地方,组件中为了使 v-model 生效,必须满足两个条件:接受一个 value 属性以及在有新的值时触发 input 事件

这是因为<inputv-model="something">是以下代码的语法糖:

<input
v-bind:value="something"
v-on:input="something = $event.target.value">


3、模板中<input :value="value" >为什么用 v-bind:value 不用 v-model?

v-model 与v-bind:value 的区别在于双向数据绑定,<input> 中的 value 属性来自父组件的传值,而 Vue.js 规定组件的数据传递prop是单向的,子组件<input>不应该在内部改变prop。这里如果使用了v-model,Vue会给如如下警告:

vue.js:482 [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "value"

这段文字解释的很清楚:(子组件内)不允许直接改变prop,因为父组件重新渲染的时候,prop的值会被覆盖。如果需要改变prop,可以基于prop的值,使用data或者computed属性。

原创粉丝点击