策码奔腾

vue子组件向父组件传值的方法

1.使用v-model

父组件使用v-model属性向子组件传值

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

  子组件使用value属性接受参数(当属性名称value被占用时可以使用model属性修改接受v-model参数的属性名称,具体可参考model的api)

然后使用$emit方法更新父组件v-model参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<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(){
1
2
3
  this.newValue = !this.newValue;
  this.$emit('update:show', this.newValue) // 父组件中的show会被更改成newValue值
}
 } }
复制代码

 

 

posted @   策码奔腾  阅读(1185)  评论(0编辑  收藏  举报
努力加载评论中...
console.log('欢迎');
点击右上角即可分享
微信分享提示