vue中的this.$emit(‘input‘,this.val);是什么意思?


子組件在傳值的時候,選用input,如this.$emit(‘input’,val),在父組件直接用v-model綁定,就可以獲取到了

而子組件也可以通過$emit(‘input’,false),去改變父組件中v-model 和 子組件中 value 的值 。
例子:

子組件

<template>
    <div>
        <div class="group">
            <label>{{title}}</label>
            <input type="text" placeholder="請輸入" @input="changeData()" v-model="val">
        </div>
    </div>
</template>

<template>
    <div>
        <div class="group">
            <label>{{title}}</label>
            <input type="text" placeholder="請輸入" @input="$emit('input', $event.target.value)"  v-model="val">
        </div>
    </div>
</template>

<script>
export default {
    props:["title"],
    data () {
        return {
            val:""
        }
    },
    methods:{
        changeData:function(){
            console.log(111);
            this.$emit('input',this.val);
        }
    }
}
</script>

父組件:

<cmsGroup title="用戶名" v-model="username"></cmsGroup>

其中,子組件this.$emit(‘input’,this.val); v-model 綁定的是 input 事件

vue 再父子組件傳值時,除了傳統的父組件 :屬性去傳值外,還可以使用 父組件v-model傳值,子組件props[‘value’]接收,

<!--父組件-->
 
<template>
   <test v-model = "isShow"></test>
   <button @click="isShow = !isShow">switch</button>
</template>
<script>
   import test from '../test';
   export default {
      components: {
         test
      },
      data() {
         return {
           isShow: false
         }
      }
   }
</script>
<!--子組件-->
 
<template>
  <div>
   <div>{{value}}</div>
   <Button @click="$emit('input',false)">關閉</Button>
  </div>
</template>
<script type="text/ecmascript-6">
    export default {
        props:['value'],
        mounted() {
            console.log(this.value)
        }
    }
</script>

 

 

 

參考---https://blog.csdn.net/qq_26642611/article/details/104055048


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM