Record two ways of writing value props in vue2 components

When writing the value transfer method, I discovered the object and array type writing methods of props. I didn’t know what the difference was, so I checked it out.

props: ["testMsg",]

This method is defined in the form of an arrayprops, where the elements of the array are the attribute names to be passed. In child components, these properties can be accessed via this.$props

<template>  
  <div>{
   
   { testMsg }}</div>  
</template>  
  
<script>  
export default {  
  name: 'ChildComponent',  
  props: ['testMsg',]  
}  
</script>

props: {name:{type:String,default:''}}

This method is defined in the form of an objectprops, where the key of the object is the attribute name to be passed, and the value of the object is an object describing the rules of the attribute. The type and default value of the attribute can be specified through this rule object

<template>  
  <div>{
   
   { name }}</div>  
</template>  
  
<script>  
export default {  
  name: 'ChildComponent',  
  props: {  
    name: {  
      type: String, // 指定属性类型为字符串  
      default: '' // 指定属性的默认值为空字符串  
    }  
  }  
}  
</script>

The parent component can pass the value of name to the child component, and the child component can obtain this value through this.$props.name. If the parent component does not pass the value of name, then the child component can get the default value (empty string) through this.$props.name

Guess you like

Origin blog.csdn.net/a99101/article/details/134669253