vue v-model 简单使用
生活随笔
收集整理的這篇文章主要介紹了
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>
主要的坑就是變量問題,已經寫在子組件里了。比傳統的父子組件傳值還是更好用的。
?
轉載于:https://www.cnblogs.com/wuyuchao/p/10423570.html
總結
以上是生活随笔為你收集整理的vue v-model 简单使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TPYBoard:一款可以发挥无限创意的
- 下一篇: html5倒计时秒杀怎么做,vue 设