Vue 父子组件间的通信

父组件向子组件传值

  1. 使用props 方式传值,父组件引用组件,使用组件后,可通过子组件内定义的 props 属性,
    使用该属性名传值到子组件内;
  2. props 可以传入String,Number,Object,Boolean,Array数据类型;
  3. prop 验证:设置required 参数 可选择是否当前属性必传;
  4. default 设置如若不传将展示的内容;
  5. props 传值为单向数据流;
    注意:子组件内不能直接修改父组件传来的props;、;

创建父组件

<template>
  <div class="root">
    <h1>this is father</h1>
     <show-name :first-name="nick_name" last-name="jack" />
  </div>
</template>
<script>
import showName from './children'
export default{
  components:{
    showName,
  },
  data(){
      return{
        nick_name:'Tom'
      }
  }
}
</script>

创建子组件

<template>
  <div class="root">
    this is children
    <p>{{first-name}}</p>
    <p>{{last-name}}</p>
  </div>
</template>
<script>
export default{
  props:{
    'first-name':{
      type:String,
      required:true,
    },
    'last-name':{
      type:String,
      default:'Jack'
    }
  },
  data(){
      return{
      
      }
  }
}
</script>

子组件向父组件传值

  1. 子组件向父组件传值,不能直接实时传递数据,必须通过事件触发。
  2. 通过 $emit 方法 实现父子间通讯;

Father

<template>
  <div class="root">
    <h1>this is father</h1>
    parent: 这是我的子组件传给我的值{{num}}
     <show-name :first-name="nick_name" last-name="jack" @getNum="getValue" />
  </div>
</template>
<script>
import showName from './children'
export default{
  components:{
    showName,
  },
  data(){
      return{
        nick_name:'Tom',
        num:''
      }
  },
  methods:{
    getValue(val){
      this.num=val;
    }
  }
}
</script>

Child

<template>
  <div class="root">
    this is children
    <p>{{first-name}}</p>
    <p>{{last-name}}</p>
    <button @click="sendValue">点击向父组件发送消息</button>
  </div>
</template>
<script>
export default{
  props:{
    'first-name':{
      type:String,
      required:true,
    },
    'last-name':{
      type:String,
      default:'Jack'
    }
  },
  data(){
      return{
        num:0
      }
  },
  methods:{
    sendValue(){
        this.$emit('getNum',this.num++);
    }
  }
}
</script>

评论

暂无评论