关于vue的APIv-model的总结
我们都知道v-model本质上是在父组件上定义了一个方法,该方法会修改传给子组件的目标值。然后在子组件上去触发相应的事件,进而触发该方法,达到双向绑定的效果。
vue提供了修改这一系列操作方便的方法。就是父组件中的子组件统一写成v-model="propName", 然后子组件中通过model配置项,定义prop的名称和对应的事件, 然后在子组件中去触发该方法即可。
就像这样:
//parent.vue 其中age是父组件中data中的一个值
<child v-mode="age"/>
<template>
<!-- child.vue -->
<div>
<button @click="$emit('customize-event', Math.random())">change</button>
{{age}}
</div>
</template>
<script>
export default {
model: {
prop: 'age',
event: 'customize-event'
},
props: {
age: {
type: Number,
default: () => 0
}
}
}
</script>
还有另外一种指令便是v-bind.sync=someObject和 this.$emit(update:xxx, xxx)的配合
<template>
<!-- parent.vue -->
<div id="app">
<Child v-bind.sync="doc"/>
</div>
</template>
<script>
import Child from './components/testA'
export default {
components: {
Child
},
data() {
return {
doc: {
title: 'title',
name: 'name'
}
}
},
}
</script>
<template>
<!-- child.vue -->
<div class="wrapper">
<div class="class1" @click="test">{{title}}</div>
</div>
</template>
<script>
export default {
props: {
title: String,
default: () => ''
},
methods: {
test() {
let str = `${Math.random()}`;
this.$emit('update:title', str)
}
}
}
</script>