组件上使用v-model
2024-08-27 04:58:24
组件上使用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 特性绑定到一个名叫
value
的prop
上- 在其 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'
接收
最新文章
- ABAP单元测试最佳实践
- c# 局域网文件传输实例
- sparkR读取csv文件
- AJXA!让体验更美好
- js面试题之数组去重对比
- Python的第二天
- Linux shell实战(ipcs工具)
- android studio logcat 换行(日志换行)
- leetcode@ [343] Integer Break (Math &; Dynamic Programming)
- MYSQL 基础操作
- iso学习网站记录
- Delphi 串口打印机打印
- GoF——组合模式
- Android OpenGL ES(九)绘制线段Line Segment .
- 你所不知道的 CSS 动画技巧与细节
- 剑指offer 08:跳台阶
- MySQL 优化小技巧
- 函数模拟sort快排
- 构建自己的 Smart Life 私有云(二)->; 连通 IFTTT &; Slack
- 使用JDBC在MySQL数据库中快速批量插入数据
热门文章
- css 文本省略号显示
- Perf -- Linux下的系统性能调优工具,第 1 部分 应用程序调优的使用和示例 Tracepoint 是散落在内核源代码中的一些 hook,一旦使能,它们便可以在特定的代码被运行到时被触发,这一特性可以被各种 trace/debug 工具所使用。Perf 就是该特性的用户之一。
- postgresql 查看用户名
- AdapterViewFlipper
- leetcode 11. Container With Most Water 、42. Trapping Rain Water 、238. Product of Array Except Self 、407. Trapping Rain Water II
- [原][工具][global mapper]查看图元属性(查看shp文件属性值)
- shell编程系列3--命令替换
- 九、postman的自带的鉴权demo
- IDEA 修改某个Module名称
- iOS 不允许横屏的简单代码