父组件
子组件
HandleList.vue
- <template>
- <div class="handle-box">
- <el-button type="primary" size="mini" @click="addFun">
- <svg-icon icon-class="add" /> <span>新建</span>
- </el-button>
- <slot />
- <div class="search">
- <el-input v-model.lazy="inValue" size="small" placeholder="请输入内容" width="200" @change="change" />
- <div class="btn">
- <svg-icon icon-class="search1" class="search1" @click.stop="change" />
- </div>
- </div>
- </div>
- </template>
- <script>
- export default {
- name: 'HandleList',
- model: {
- prop: 'modelValue',
- event: 'returnModel'
- },
- props: {
- // 新建
- add: {
- type: Boolean,
- default: true
- },
- // 输入框
- search: {
- type: Boolean,
- default: true
- },
-
- modelValue: String
-
- },
- data() {
- return {
- inputVal: this.value
- }
- },
- computed: {
- inValue: {
- get: function() {
- // 获取传入的v-model
- return this.modelValue
- },
- set: function(newValue) {
- // 修改时同时修改v-model
- this.$emit('returnModel', newValue)
- return newValue
- }
- }
- },
- watch: {
- },
- methods: {
- change() {
- console.log('到了这里')
- this.$emit('change')
- },
- addFun() {
- this.$emit('add')
- }
-
- }
- }
- </script>
- <style lang="scss" scoped>
- .modal {
- .slot-title {
- width: 100%;
- height: 28px;
- font-family: PingFangSC-Semibold;
- font-size: 20px;
- color: #2088ff;
- letter-spacing: 0;
- font-weight: 600;
- }
-
- /deep/ .el-dialog__header {
- border-bottom: 1px solid $lightgrey;
- }
-
- /deep/ .el-dialog__body {
- padding: 20px 20px;
- }
-
- /deep/ .el-dialog__footer {
- border-top: 1px solid $lightgrey;
- padding: 15px 20px;
-
- .btn {
- width: 104px;
- height: 32px;
- padding: 0px;
- border-radius: 2px;
- }
- }
- }
- </style>
- model父组件v-mode传入的数据
- prop :对应prop的modelValue
- event:修改v-model的事件
props: {
modelValue: String
}
- 不能直接操作modelValue. 数据向下,事件向上原则
computed: {
inValue: {
get: function() {
// 获取传入的v-model
return this.modelValue
},
set: function(newValue) {
// 修改时同时修改v-model
this.$emit('returnModel', newValue)
return newValue
}
}
},用computed 的计算一个新的参数 给el-input 绑定
如果要实现
v-model.lazy 效果
需要在子组件上
<el-input v-model.lazy="inValue" size="small" placeholder="请输入内容" width="200" @change="change" />change() {
console.log('到了这里')
this.$emit('change')
},
父组件
@change="fetch">
model父组件v-mode传入的数据
prop :对应prop的modelValue
event:修改v-model的事件
为什么不直接 v-model 绑定 modelValue
因为el-input修改同时会修改modelValue然后vue的prop数据是不允许被子组件修改的
因此需要对应的event修改
为了显示数据inValue单向绑定,set调用returnModel,get获取v-model值
扩展点:
v-model语法糖 是:value @input 实现
这个可能是个面试题
注:我只是复制了部分代码,部分props参数逻辑没写完,抛砖引玉