简单的例子 没有多余代码,

父传子

<template>
//父组件 引用子组件aaa 两种写法传递num1,num2
  <div>
   <aaa v-bind:father1="num1" :father2="num2"></aaa>
  </div>
</template>
<script>
import aaa from './aaa'
export default {
  data () {
    return {
      num1:'111',
      num2:'222',
    }
  },
  components:{
    aaa
  }
}
</script>
<style scoped>

</style>

子组件

<template>
//两种prop接收写法,
  <div>
    <h3>子组件</h3>
    <h2>{{father1}}</h2>
    <h2>{{father2}}</h2>
  </div>
</template>
<script>
  export default {
    // props:['father1','father2']
    props:{
      father1:String,
      father2:String
    }
  }
</script>

在这里插入图片描述

子传父

点击’获取子组件的值’页面显示444

<template>
  <div>
    <h3>父组件传的值</h3>
    <h2>{{father1}}</h2>
    <h2>{{father2}}</h2>
    <h3 @click="fn">获取子组件的值</h3>
  </div>
</template>
<script>
  export default {
    // props:['father1','father2']
    props:{
      father1:String,
      father2:String
    },
    data() {
      return {
        childNum:'444'
      }
    },
    methods: {
      fn(){
        this.$emit('listenEvent',this.childNum)
      }
    },
  }
</script>

<template>
  <div class="hello">
   <!-- <div>练习:{{num}}</div> -->
   <aaa v-bind:father1="num1" :father2="num2" @listenEvent="fn"></aaa>
   <h3>{{num3}}</h3>
  </div>
</template>

<script>
import aaa from './aaa'
export default {
  data () {
    return {
      num1:'111',
      num2:'222',
      num3:'',
      
    }
  },
  components:{
    aaa
  },
  methods: {
    fn(params){
      this.num3 = params
    }
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

在这里插入图片描述

写法
props: {
  fieldString: String,
  fieldNumber: Number,
  fieldBoolean: Boolean,
  fieldArray: Array,
  fieldObject: Object,
  fieldFunction: Function
}
带有默认值写法
props: {
    fieldString: {
      type: String,
      default: ''
    },
    fieldNumber: {
      type: Number,
      default: 0
    },
    fieldBoolean: {
      type: Boolean,
      default: true
    },
    fieldArray: {
      type: Array,
      default: () => []
    },
    fieldObject: {
      type: Object,
      default: () => ({})
    },
    fieldFunction: {
      type: Function,
      default: function () { }
    }
  }
  props: {
   // 基础的类型检查 (`null` 和 `undefined` 会通过任何类型验证)
   propA: Number,
   // 多个可能的类型
   propB: [String, Number],
   // 必填的字符串
   propC: {
     type: String,
     required: true
   },
   // 带有默认值的数字
   propD: {
     type: Number,
     default: 100
   },
   // 带有默认值的对象
   propE: {
     type: Object,
     // 对象或数组默认值必须从一个工厂函数获取
     default: function () {
       return { message: 'hello' }
     }
   },
   // 自定义验证函数
   propF: {
     validator: function (value) {
       // 这个值必须匹配下列字符串中的一个
       return ['success', 'warning', 'danger'].indexOf(value) !== -1
     }
   }
 }
Logo

前往低代码交流专区

更多推荐