Vue props 配置项及数据类型

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

  • 传递数据 这个age前加 : , 通过v-bind 是的里面的18是数字

  • 接收数据

    • 第一种方式(只接收) props:[‘name’,'age]
    • 第二种(限制类型) props:{name:String,age:Number}
    • 第三种(限制类型、限制必须性、指定默认值)
props: {
    
    
    name: {
    
    
        type: String,	 // 类型
        required: true,// 必要性
        default: 'cess'// 默认值
    }
}

限制类型如下:

1.String 字符串

2.Number 数字

3.Boolean 布尔

4.Array 数组

5.Object 对象

6.Date 日期

7.Function 函数

8.Symbol 独一无二的(ES6)

default:

  • 基础数据类型: 直接赋值
  • 对象数据类型: 用函数赋值 ()->{}

required:

required: 必填项

默认为false,说明父级必须传入,否则报错

validator:

校验(验证传入的值是否符合规定)

src/App.vue

<template>
  <div>
    <Student name="李四" sex="女" :age="18"/>
    <Student name="王五" sex="男" :age="18"/>
  </div>
</template>

<script>
  import Student from './components/Student'

  export default {
    
    
    name:'App',
    components:{
    
     Student }
  }
</script>

src/components/Student.vue

<template>
  <div>
    <h1>{
    
    {
    
     msg }}</h1>
    <h2>学生姓名:{
    
    {
    
     name }}</h2>
    <h2>学生性别:{
    
    {
    
     sex }}</h2>
    <h2>学生年龄:{
    
    {
    
     myAge + 1 }}</h2>
    <button @click="updateAge">尝试修改收到的年龄</button>
  </div>
</template>

<script>
export default {
    
    
  name: "Student",
  data() {
    
    
    console.log(this);
    return {
    
    
      msg: "我是一个UESTC大学的学生",
      myAge: this.age,
    };
  },
  methods: {
    
     updateAge() {
    
     this.myAge++; }, },
  // 简单声明接收
  // props:['name','age','sex']

  // 接收的同时对数据进行类型限制
  //   props: {
    
    
  //     name: String,
  //     age: Number,
  //     sex: String,
  //   }

  // 接收的同时对数据:进行类型限制+默认值的指定+必要性的限制
  props: {
    
    
    name: {
    
    
      type: String, 	//name的类型是字符串
      required: true, //name是必要的
    },
    age: {
    
    
      type: Number,
      default: 99, //默认值
    },
    sex: {
    
    
      type: String,
      required: true,
    },
  },
};
</script>

猜你喜欢

转载自blog.csdn.net/fd2025/article/details/125326715
今日推荐