组件上使用v-model

<input v-model="searchText">

等价于

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

当用在组件上时,v-model则会这样:

<custom-input v-model="searchText"></custom-input>

等同于

<custom-input
v-bind:value="searchText"
v-on:input="searchText = $event"
></custom-input>

为了让它正常工作,这个组件内的<input>必须:

  • 将其 value 特性绑定到一个名叫valueprop
  • 在其 input 事件被触发时,将新的值通过自定义的input事件抛出
Vue.component('custom-input', {
props: ['value'],
template: `
<input
v-bind:value="value"
v-on:input="$emit('input', $event.target.value)"
>
`
})

现在v-model就应该可以在这个组件上完美地工作起来了:

<custom-input v-model="searchText"></custom-input>

示例

父组件App.vue中

<template>
<div id="app">
<Model v-model="searchText"></Model>
<span>{{searchText}}</span>
<!-- 等价于
<custom-input
v-bind:value="searchText"
@input="searchText = $event"
></custom-input> -->
</div>
</template>
<script>
import Model from "./components/Model"; export default {
name: "App",
data: function() {
return {
searchText:''
};
},
components: {
Model
}
};
</script>

子组件model.vue

<template>
<div id="app">
<input v-bind:value="value" @input="$emit('input', $event.target.value)">
</div>
</template>
<script>
export default {
props: ["value"], };
</script>

过程:

1.输入文字

2.:value='search' 传给子组件

3.子组件props接收

4.子组件:value='value'

5.子组件绑定input通过$emit传给父组件

6.父组件@input='searchText = $event'接收

最新文章

  1. ABAP单元测试最佳实践
  2. c# 局域网文件传输实例
  3. sparkR读取csv文件
  4. AJXA!让体验更美好
  5. js面试题之数组去重对比
  6. Python的第二天
  7. Linux shell实战(ipcs工具)
  8. android studio logcat 换行(日志换行)
  9. leetcode@ [343] Integer Break (Math &amp; Dynamic Programming)
  10. MYSQL 基础操作
  11. iso学习网站记录
  12. Delphi 串口打印机打印
  13. GoF——组合模式
  14. Android OpenGL ES(九)绘制线段Line Segment .
  15. 你所不知道的 CSS 动画技巧与细节
  16. 剑指offer 08:跳台阶
  17. MySQL 优化小技巧
  18. 函数模拟sort快排
  19. 构建自己的 Smart Life 私有云(二)-&gt; 连通 IFTTT &amp; Slack
  20. 使用JDBC在MySQL数据库中快速批量插入数据

热门文章

  1. css 文本省略号显示
  2. Perf -- Linux下的系统性能调优工具,第 1 部分 应用程序调优的使用和示例 Tracepoint 是散落在内核源代码中的一些 hook,一旦使能,它们便可以在特定的代码被运行到时被触发,这一特性可以被各种 trace/debug 工具所使用。Perf 就是该特性的用户之一。
  3. postgresql 查看用户名
  4. AdapterViewFlipper
  5. leetcode 11. Container With Most Water 、42. Trapping Rain Water 、238. Product of Array Except Self 、407. Trapping Rain Water II
  6. [原][工具][global mapper]查看图元属性(查看shp文件属性值)
  7. shell编程系列3--命令替换
  8. 九、postman的自带的鉴权demo
  9. IDEA 修改某个Module名称
  10. iOS 不允许横屏的简单代码