vue v-model 简单使用

 最近在写组件时,考虑到子组件的状态需要实时反馈给父组件,于是想起来了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>

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

猜你喜欢

转载自www.cnblogs.com/wuyuchao/p/10423570.html