最近在写组件时,考虑到子组件的状态需要实时反馈给父组件,于是想起来了v-model,下面介绍一下自定义组件中的简单使用

官网介绍不是很清晰,这个默认的input事件很容易让人产生误解,其实个人建议还是不要使用默认的prop和event,尽量重新定义。

我的子组件

<template>
<div>
<el-select v-model="id" style="margin-bottom:20px" @change="handleChange" :multiple="multiple">
<el-option class="item" v-for="item in channelArr" :key="item.channel" :label="item.channel + ' ' + item.name" :value="item.channel">
<div v-if="item.pic"><img class="item-icon" :src="item.pic" alt=""><span>{{item.channel + ' ' + item.name}}</span></div>
</el-option>
</el-select>
</div>
</template> <script>
import {
getChannelAPI,
} from '@/api/data'
export default {
name: 'UserChannel',
model: {
prop: 'id', // 坑点 这里官方文档和props是一个名字,都是checked 但在使用过程中会报错,多番排查后, 将model里的prop新定义一个名字,为了保证和props里父组件传过来的channelId一致,在子组件data中进行赋值,就不再报错了。
event: 'change' // event 名称可以随便起 emit 里对应就行,这里配合业务起的是change
},
// 如果model不写就会走默认的model prop:value , event : input 不要被input所迷惑,并不一定代表js的oninput事件
props: {
hasChange:{
type: Boolean,
default: false
},
channelId:{
type:String,
default:''
},
multiple:{
type:Boolean,
default:false
}
},
data() {
return {
channelArr: [],
id:this.channelId
}
},
created(){
this.getChannel()
},
methods: {
getChannel() {
if (this.channelArr.length == 0) {
getChannelAPI().then(response => {
this.channelArr = response.data.channeArr;
}); }
},
handleChange(event){
// this.$emit('someProp', [returnValueToParent]) returnValueToParent 是什么,父组件的v-model 就是多少
this.$emit('change', event);
if(this.hasChange){
this.$emit('fetch', event)
}
},
}
}
</script>
<style scoped>
.item{
margin-bottom: 6px;
}
.item-icon{
width: 30px;
height: 30px;
vertical-align: middle;
border-radius: 50%;
margin-right: 20px;
}
</style>

父组件

<template>
<div>
<user-channel v-model="channel"></user-channel>
    
</div>
<template> <script>
import UserChannel from '@/components/UserChannel'
export default {
components:{
UserChannel
},
data() {
return {
channel:''
}
......
</script>

主要的坑就是变量问题,已经写在子组件里了。比传统的父子组件传值还是更好用的。

最新文章

  1. 探讨Js的事件的冒泡阶段
  2. 解锁scott用户及设置密码
  3. Windows Azure Web Site (7) Web Site配置
  4. Bootstrap弹窗插件(拟态框)关闭后回调函数
  5. ECshop设置301最快捷最简单的方法
  6. Android SDK Manager 在win8.1上的闪退问题
  7. 通过HttpClient来调用Web Api接口
  8. Arduino+RFID RC522 +继电器
  9. 字符串拼接 strcat ;数组和指针的区别
  10. Servlet实现文件上传(简单)(一)
  11. jQuery:下拉列表的联动
  12. sys用户密码丢失找回密码的步骤和命令
  13. 如何预览Github上的页面
  14. 20170725 Python 必须使用的Url编码
  15. Spring核心简介
  16. 牛客训练五:炫酷路途(c++与dp)
  17. python之三级菜单作业
  18. Node.js学习笔记(八) --- Node.js的路由模块封装
  19. Spring-DispatcherServlet说明
  20. 【Android M】预制的 Google GMS包

热门文章

  1. JS中的匿名函数自执行、函数声明与函数表达式
  2. tap事件的原理详解
  3. Linux网络知识
  4. 搭建简单的node+express+mongodb项目
  5. 前端开发必知必会:CSS Position 全解析
  6. 【BZOJ】1426: 收集邮票 期望DP
  7. ES6 中 Array.from() 不能得到的数组元素是 undefined 或是空数组
  8. Spring Boot工程结构推荐
  9. 21、利用selenium进行Web测试
  10. MM(Majorize-Minimization, Minorize-Maximization)优化方法