Vue子组件props属性

一个组件如果直接展示(比如第一次展示)在不同的地方需要data不一样的内容时候,如果不使用后端交互,就比较难了,这时可以用props属性。

1. props属性配置步骤

props功能: 让组件接收外部传过来的数据

  1. 传递数据: <Demo name="xxx">
  2. 接收数据:
  • 第一种方式(只接收): props:['name'] 必须名称是字符串
  • 第二种方式(限制类型): props:{name: String}
  • 第三种方式(限制类型,限制必要性、指定默认值):
js
props: {
    name:{
        type: String, // 类型
        required: true, // 必要性
        default: '老王'  // 默认值
    }
}

警告

props是只读的,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求确实需要修改,那么请复制props的内容到data中一份,然后去修改data中的数据。

vue
<template>

  <div>

    <img alt="Vue logo" src="./assets/logo.png">

    <!-- 有时候你会发现有些属性传值加有冒号,是因为传入的值不是字符值(字符串),比如数字、对象(data属性里面的),要做区分,-->

    <!-- 比如这里的999,如果是字符串999的话,School组件内部studentNum的值就是变成字符串拼接成9991而不是1000 --> 

    <School schoolName="湘雅医学院" :studentNum ="999"></School>

  </div>

</template>



<script>

import School from "@/components/School.vue";



export default {

  name: 'App',

  components: {

    School

  },

}

</script>
vue
<template>

  <div class="hello">

    <h2>学校名字:{{ schoolName }}</h2>

    <h2>学校地址: {{ schoolAddress }}</h2>

    <h2>学生人数: {{ studentNum+1 }}</h2>

  </div>

</template>

<script>

export default {

  name: 'School',

  props: ['schoolName', 'studentNum' ],

  data() {

    console.log(this);

    return {

      schoolAddress: '四川'

    }

  }

}

</script>
运行效果: ![Alt text](/web/vue/images/1708654607469.jpg)

2. 如何区分组件自带的属性和props传入的属性呢?

可以查看vue开发者工具: Alt text 办法二:可以查看vc实例对象上面的_data属性就是自身的 Alt text

3. props属性的高级配置

前面说到如果组件传值如果不是字符串类型需要加上:才行,实际开发中如何限制别人使用自己的组件按照数据类型要求进行传值呢?

vue
<template>
  <div class="hello">
    <h2>{{ msg }}</h2>
    <h2>学校名字:{{ schoolName }}</h2>
    <h2>学校地址: {{ schoolAddress }}</h2>
    <h2>学生人数: {{ studentNum + 1 }}</h2>
  </div>
</template>

<script>
export default {
  name: 'School',
  props: {
    'schoolName': {
      required: true,
      type: String,
      validator(value) {
        return value.length < 5
      }
    }, 'studentNum': {
      required: true,
      type: Number
    }
  },
  data() {
    return {
      msg: '欢迎大家!!',
      schoolAddress: '四川'
    }
  }
}
</script>

运行效果: Alt text

4. 如果子组件props写没有传入的值名字会怎么样?

vc实例上面将会是undifined: Alt text

5. 如果子组件props传入的值名字和data中属性名称一样会怎么样?

将会报错,并且data中属性不起作用,可见props中的优先级更高 Alt text 解决办法: 就是data中对应的属性重命名

6. 如果组件props传入的值名字有限制不?

限制有的, Vue已经占用了一些名字,比如ref, key都不能用, 解决办法就是改名 Alt text 运行结果: Alt text

评论