策码奔腾

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值
      }
 } }

 

 

posted @ 2021-01-15 18:09  策码奔腾  阅读(1171)  评论(0编辑  收藏  举报
console.log('欢迎');