前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >vue v-model 简单使用

vue v-model 简单使用

作者头像
吴裕超
发布2019-05-25 17:55:31
8120
发布2019-05-25 17:55:31
举报
文章被收录于专栏:吴裕超

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

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

我的子组件

代码语言:javascript
复制
<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>

父组件

代码语言:javascript
复制
<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>
    

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-03-06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档