本文介绍了vue v-model进行数据绑定,分享给大家,具体如下
官方例子https://vuefe.cn/v2/api/#model
有这么一句话: 默认情况下,一个组件上的 v-model 会把 value 用作 prop 且把 input 用作 event。
示例:
先来一个组件,不用vue-model,正常父子通信
<!-- parent --><template><p class="parent"> <p>我是父亲, 对儿子说: {{sthGiveChild}}</p> <Child @returnBack="turnBack" :give="sthGiveChild"></Child></p></template><script>import Child from './Child.vue';export default { data() { return { sthGiveChild: '给你100块' }; }, components: { Child }, methods: { turnBack(val) { this.sthGiveChild = val; } }}</script>
<!-- child --><template><p class="child"> <p>我是儿子,父亲对我说: {{give}}</p> <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" @click="returnBackFn">回应</a></p></template><script>export default { props: { give: String }, methods: { returnBackFn() { this.$emit('returnBack', '还你200块'); } }}</script>
点击回应后,父亲对儿子说的话变成了儿子的回应。儿子收到的信息也变了,实现通信。
改用v-model
<!-- parent --><template><p class="parent"> <p>我是父亲, 对儿子说: {{sthGiveChild}}</p> <Child v-model="sthGiveChild"></Child></p></template><script>import Child from './Child.vue';export default { data() { return { sthGiveChild: '给你100块' }; }, components: { Child }}</script>
<!-- child --><template><p class="child"> <p>我是儿子,父亲对我说: {{give}}</p> <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" @click="returnBackFn">回应</a></p></template><script>export default { props: { give: String }, model: { prop: 'give', event: 'returnBack' }, methods: { returnBackFn() { this.$emit('returnBack', '还你200块'); } }}</script>
文案虽有不同,但是效果最终是一致的。
看看官方自定义组件的v-model
官方例子https://vuefe.cn/v2/api/#model
有这么一句话: 默认情况下,一个组件上的 v-model 会把 value 用作 prop 且把 input 用作 event。
尝试把上边子组件的例子改一下,也是跑的通的
<!-- child --><template><p class="child"> <p>我是儿子,父亲对我说: {{value}}</p> <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" @click="returnBackFn">回应</a></p></template><script>export default { props: { value: String }, methods: { returnBackFn() { this.$emit('input', '还你200块'); } }}</script>
新闻热点
疑难解答
图片精选