将原生事件绑定到组件
<div id="app">
<base-input v-on:focus="onFocus" v-model="message" label="姓名"></base-input>
</div>
<script>
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>
`,
})
new Vue({
el: '#app',
data() {
return {
message: 'sss'
}
},
methods: {
onFocus(val) {
console.log(val)
}
},
})
</script>
.sync 修饰符
prop—父子传值
<div id="app">
<father />
</div>
Vue.component('father', {
template: `
<div>
<div @click="isShow">切换</div>
<son v-if="show" @isShow='isShow'></son>
</div>
`,
components: {
son: {
template: `
<div>
<div @click="fn">隐藏</div>
</div>
`,
methods: {
fn() {
this.$emit('isShow', false)
}
}
}
},
data() {
return {
show: true
}
},
methods: {
isShow(val) {
console.log(val);
this.show = !this.show
}
},
})
使用 .sync
// <son v-if="show" @update:isShow='show = $event'></son>
// <son v-if="show" :isChange.sync='show'></son> // 当子触发this.$emit('update:isChange', false),这里的show = this.$emit('update:isChange', false) 传的 false
Vue.component('father', {
template: `
<div>
<input v-model='show'></input>
<div @click="isShow">切换</div>
<son v-if="show" :isChange.sync='show'></son>
</div>
`,
components: {
son: {
props: ['isChange'],
template: `
<div>
<div @click="fn">隐藏</div>
</div>
`,
methods: {
fn() {
this.$emit('update:isChange', false)
}
},
watch: {
isChange(val) {
console.log(val);
}
}
}
},
data() {
return {
show: true
}
},
methods: {
isShow(val) {
console.log(val);
this.show = !this.show
}
}
})
new Vue({
el: '#app',
data() {
return {
message: 'sss'
}
},
})
注意:.sync官方给出的解释就是一种语法糖的意思
最后:sync只是给大家伙提供了一种与父组件沟通的思路而已!如果只是单纯的在子组件当中修改父组件的某个数据时,建议使用sync,简单,快捷,不需要在传一个自定义方法来接收了