Skip to content

props 配置

功能

让组件接收外部传递过来的数据。

组件传参

  1. 直接在组件标签上写上数据即可。

  2. Vue
    <Student :info="info"></Student>
  3. 注意,如果这里只需要穿一些字符串,在 info 前面不需要用 v-bind 绑定。

组件接参

  1. 第一种写法

    js
    props: [参数1,参数2,……,参数n]
  2. 第二种写法:限制类型

    javascript
    props: {
    	参数1: 类型(Number,String,Object,Array……),
      ……
      参数n: 类型
    }
  3. 第三种写法:限制类型、限制必要性、指定默认值。

    javascript
    props: {
        参数1: {
            type: 类型(Number,String,Object,Array……),
            required: 是否为必传参数(true || false),
            default: 默认值
        },
        参数2: {
          
        }
    }

注意事项

  1. props 是只读的,也就是说,在组件内部是无法修改 props 中的数据的。Vue 底层会检测你对 props 的修改,如果进行了修改,就会发出警告。
  2. 如果想修改 props 中的数据,可以将其拷贝一份,并放在 data 中,然后修改 data 中的数据。

案例

需求

  1. 定义一个 Student 组件。
  2. 在 App 组件中引用这个组件,并传递参数。
  3. 在 Student 组件中加一个按钮,点击按钮改变学生的年龄。

代码实现

  1. App.vue

    html
    <template>
        <div>
            <Student :info="info"></Student>
        </div>
    </template>
    
    <script>
        import Student from './components/Student.vue'
        export default {
            name: 'App',
            components: {Student},
            data(){
                return {
                    info: {
                        name: '张三',
                        age: 21,
                        sex: '男'
                    }
                }
            }
        }
    </script>
  2. Student.vue

    html
    <template>
        <div>
            <h3>学生姓名:{{ info.name }}</h3>
            <h3>学生性别:{{ info.sex }}</h3>
            <h3>学生年龄:{{ age }}</h3>
            <button @click="age++">点我年龄 + 1</button>
            <hr>
        </div>
    </template>
    
    <script>
        export default {
            name: 'Student',
            props: ['info'],
            data(){
                return {
                    age: this.info.age
                }
            }
        }
    </script>

基于 MIT 许可发布