vue子組件向父組件傳值的方法


1.使用v-model

父組件使用v-model屬性向子組件傳值

<cmbtpop v-model="show"  :name="entity.name" ></cmbtpop>

  子組件使用value屬性接受參數(當屬性名稱value被占用時可以使用model屬性修改接受v-model參數的屬性名稱,具體可參考model的api)

然后使用$emit方法更新父組件v-model參數

<div :show="newValue" @click="changeValue" >{{name}}</div>

export default {
  name: 'cmbtpop',


   data() {
    return {
        newValue : this.value,//使用newValue 控制子組件
    
    };
  },
  
  props: {
    value:{ 
      type:Boolean,
      default: false
      }  ,
    name: String
  },
  watch:{
           value:function(){
             this.newValue = this.value;//父組件的show值改變時重新控制子組件
           }
          
        },

  methods:{
      changeValue(){ 
        this.newValue = !this.newValue;
        this.$emit('input', this.newValue) // 父組件中的show會被更改成newValue值
      }
  }
}

  2.使用同步后綴sync

  在父組件的傳參屬后加入.sync標明該屬性同步

        在子組件中使用$emit方法更新父組件同步屬性

<cmbtpop show.sync="show"></cmbtpop>





//子組件
export default {
    props: {
      show: {
        type: Boolean,
        default: false
      }
    },
    methods:{
      changeValue(){
        this.newValue = !this.newValue;
        this.$emit('update:show', this.newValue) // 父組件中的show會被更改成newValue值
      }
 } }

 

 


免責聲明!

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



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