Event name: Always use the name of the event kebab-case
Different from the assembly and prop, event name any automatic case conversion does not exist . But the name of the event triggering the need for exact match for the name of the event monitor used
Different from the assembly and prop, event names will not be used as a JavaScript variable or attribute names, so there is no reason to use a camelCase or PascalCase.
And v-on
event listeners are automatically converted in the DOM template for all lowercase (since HTML is not case-sensitive),
It v-on:myEvent
will become v-on:myevent
- cause myEvent
can not be monitored.
Custom components v-model:model选项设置绑定的prop和事件
v-model itself is to deal with!
The native event bound to the component (within the component processing: $ listeners .native)
To solve this problem, Vue provides a $listeners
property , it is an object, which contains the effect on this component of all listeners
With this $listeners
property, you can fit all the event listeners of a particular child point of this component v-on="$listeners"
Vue.component('base-input', { inheritAttrs: false, props: ['label', 'value'], computed: { inputListeners: function () { var vm = this // `Object.assign` 将所有的对象合并为一个新对象 return Object.assign({}, // 我们从父级添加所有的监听器 this.$listeners, // 然后我们添加自定义监听器, // 或覆写一些监听器的行为 { // 这里确保组件配合 `v-model` 的工作 input: function (event) { vm.$emit('input', event.target.value) } } ) } }, template: ` <label> {{ label }} <input v-bind="$attrs" v-bind:value="value" v-on="inputListeners" > </label> ` })
自定义组件的 v-model
一个组件上的 v-model
默认会利用名为 value
的 prop 和名为 input
的事件,
v-model
默认会利用名为 value
的 prop 和名为 input
的事件,但是像单选框、复选框等类型的输入控件可能会将 value
特性用于不同的目的。
value
特性用于不同的目的。model
选项可以用来避免这样的冲突:
model
选项可以用来避免这样的冲突:Vue.component('base-checkbox', { model: { prop: 'checked', event: 'change' }, props: { checked: Boolean }, template: ` <input type="checkbox" v-bind:checked="checked" v-on:change="$emit('change', $event.target.checked)" > ` }) <base-checkbox v-model="lovingVue"></base-checkbox>
注意你仍然需要在组件的 props
选项里声明 checked
这个 prop。
.sync
修饰符:2.3.0+ 新增,
单个属性/多个属性:做了很多事情:v-bind:title.sync
在有些情况下,我们可能需要对一个 prop 进行“双向绑定”。不幸的是,真正的双向绑定会带来维护上的问题,因为子组件可以修改父组件,且在父组件和子组件都没有明显的改动来源。
这也是为什么我们推荐以 update:myPropName
的模式触发事件取而代之。
this.$emit('update:title', newTitle)//子组件发送,为了配合sync,必须用update:title,"值"这种格式 //父组件接受 <text-document v-bind:title="doc.title" v-on:update:title="doc.title = $event" ></text-document> 为了方便起见,我们为这种模式提供一个缩写,即 .sync 修饰符: <text-document v-bind:title.sync="doc.title"></text-document>
this.$emit('update:title', newTitle)//子组件发送,为了配合sync,必须用update:title,"值"这种格式
当我们用一个对象同时设置多个 prop 的时候,也可以将这个 .sync
修饰符和 v-bind
配合使用:
<text-document v-bind.sync="doc"></text-document>
组件内:像下面这样写,这样父元素就能自动监听元素
这样会把 doc
对象中的每一个属性 (如 title
) 都作为一个独立的 prop 传进去,然后各自添加用于更新的 v-on
监听器。