Vue2中的props属性的介绍以及使用案例

Vue2中的props属性的介绍以及使用案例

什么是props属性?

在Vue中,props属性用于在父组件和子组件之间传递数据。父组件可以通过props属性向子组件传递数据,子组件则可以接收并使用这些数据。props属性可以被认为是一种从父组件向子组件传递数据的方式,类似于函数的参数传递。

如何使用props属性?

在Vue2中,使用props属性需要以下几个步骤:

1. 在子组件中声明props属性

在子组件中,可以使用props选项声明需要接收的属性。props选项是一个数组或对象,用于指定子组件可以接收的属性名称和类型。

Vue.component('child-component', {
  props: ['message'],
  template: '<div>{{ message }}</div>'
});

在上面的例子中,子组件声明了一个props属性message,用于接收父组件传递的数据。

2. 在父组件中传递数据给子组件

在父组件中,可以通过在子组件标签上使用属性来传递数据给子组件。属性的名称应与子组件中声明的props属性名称相对应。

<child-component message="Hello, Vue!"></child-component>

在上面的例子中,父组件通过:message属性向子组件传递了一个字符串数据。

3. 子组件中使用props属性

在子组件中,可以通过this关键字访问props属性,并在模板中使用它们。

Vue.component('child-component', {
  props: ['message'],
  template: '<div>{{ message }}</div>'
});

在上面的例子中,子组件通过this.message访问props属性,并在模板中使用它来显示数据。

示例:使用props属性传递数据

下面是一个简单的示例,演示了如何在Vue2中使用props属性传递数据:

<!-- 父组件 -->
<template>
  <div>
    <h1>父组件</h1>
    <child-component message="message"></child-component>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      message: 'Hello, Vue!'
    };
  }
};
</script>

<!-- 子组件 -->
<template>
  <div>
    <h2>子组件</h2>
    <div>{{ message }}</div>
  </div>
</template>

<script>
export default {
  props: ['message']
};
</script>

在上面的示例中,父组件通过message属性向子组件传递了一个字符串数据,并在子组件中使用props属性来显示该数据。

注意:直接通过message传入的内容为字符串的形式,子组件接收到的也是字符串的形式,如果想要接收到的格式为数字类型则需要以:message="123"的形式在父组件处传入,才能进行数学运算。

props的其他书写形式

形如:props:['message']的数组接收形式为简写形式

其较为完整的书写形式如下:

props:{
        name:String,
        website:String,
        websiteName:String
    }

可以进行类型限制等操作。

而最完整的形式如下:

props:{
        name:{
            type:String,//name传入的类型为字符串
            require:true,//name是必须的
            default:"未传入"//name的默认值是未传入,一般必须和默认值同时只会出现一个
        },
        website:String,
        websiteName:String
    }
© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容