Vue学习小札——2.6 组件参数校验与非props特性

220 阅读1分钟

  <div id="app">
    <child content="{'a':1}"></child>
  </div>
   
  <script>
   Vue.component('child',{
    // props: ['content'],
    //组件参数校验
    props: {
      //content:String,
      // content: [String, Number],
      content: {
        type: String,
        required: true,
        default:'defaultValue',
        validator: function(value) {
          return (value.length > 5)
        }
      }
    },
    template: '<div>{{content}}</div>',
   })
   var vm = new Vue({
     el: "#app",
   });
  </script>


父组件通过属性content向子组件传递参数,子组件通过props接受,

props: ['content'],


子组件也可以对父组件传过来的参数进行校验,判断参数是否未String类型

props: {
       content:String
       }


判断参数是否为String或者Number类型

props: {
      content: [String, Number]
      }


type判断参数类型,requried是否为必传参数,default默认值 当父组件没有传参数给子组件时显示,validator函数自定义其他校验

props: {
      content: {
        type: String,
        required: true,
        default:'defaultValue',
        validator: function(value) {
          return (value.length > 5)
          //如果value.length > 5 ,则返回true
         }
      }



props特性 VS 非props特性

props特性:指的是当你的父组件使用子组件的时候,通过属性向子组件传值的时候,恰好子组件里声明了对父组件传递过来的属性的接受。(父组件调用子组件传递了content,子组件恰好再props里声明了content)。

1.可以在子组件使用父组件传过来的数据

2.不会把属性显示在dom之中


非props特性:指的是父组件向子组件传递一个属性,子组件并没有声明接受父组件传递过来的内容。

1.无法使用

2.属性会展示在子组件最外层的dom标签的html里。