父传子的两种方式

静态属性传参

  1. 在不定义 props 类型的情况下 props 接受到的均为 String。
  2. 当 props 属性指定为 Boolean 时,并且只有属性 key 没有值 value 时接受到的是 true

动态属性传参

  1. 若是表达式,则获取表达式的值 ```vue

  1. 子组件使用props接收
  2. ```vue
  3. <template>
  4. <view>
  5. <view :class="color">{{ title }}</view>
  6. <image :src="icon"></image>
  7. <view>{{num}}</view>
  8. </view>
  9. </template>
  10. <script>
  11. export default {
  12. props: {
  13. title: {
  14. type: [String, Number], // 类型
  15. default: "确定" // 默认值
  16. },
  17. icon: {
  18. type: [String],
  19. default: ""
  20. },
  21. num: {
  22. type: [Number],
  23. default: "1"
  24. }
  25. }
  26. }
  27. </script>

子传父

子组件使用$emit

  1. <script>
  2. export default {
  3. data() {
  4. return {
  5. result: '成功啦!',
  6. }
  7. },
  8. methods: {
  9. goFather() {
  10. // 通过$emit的进行传递
  11. // toFather:自定义父组件事件名称
  12. // this.result:传递给父组件的值
  13. this.$emit('toFather', this.result)
  14. },
  15. },
  16. created() {
  17. this.goTo()
  18. },
  19. }
  20. </script>

父组件接收

  1. <template>
  2. <view>
  3. <view>子组件的值:{{ result }}</view>
  4. <!-- @toFather:子定义的事件名称 getResult:父定义的事件处理函数 -->
  5. <son-1 @toFather="getResult"></son-1>
  6. </view>
  7. </template>
  8. <script>
  9. export default {
  10. data() {
  11. return {
  12. result: '',
  13. }
  14. },
  15. methods: {
  16. // 此时参数为子组件传递的值
  17. getResult(e) {
  18. this.result = e
  19. },
  20. },
  21. }
  22. </script>