vue学习【组件参数校验与非props特性】

什么是props?
当父组件使用子组件时,通过属性向子组件传值时,子组件需要在props中声明这一属性,才能接收到父组件传来的值。同时可以在props中对该参数做校验。
非props特性

  1. 会将父标签中定义的content="hell"传到页面上,在页面检查的html标签中可以看到。
  2. 没有props的话,在子组件的template中使用{{content}}是无法使用的,因为没有接收到父组件传来的content值,相当于没有定义。
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>组件参数的校验</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
    <child content="hello"></child>
    <!--    <child></child>-->
</div>
</body>
</html>
<script>
    Vue.component('Child', {
        props: {
            // content: Number
            // content: String
            // content: [Number, String],  // 传入的content类型需要是String或者是数字
            content: {
                type: String,
                required: true,   // content 必须要传值
                default: 'default value',
                validator: function (value) { //自定义校验器
                    return (value.length > 5)
                }
            }
        },
        template: '<div>{{content}}</div>'
    })
    var vm = new Vue({
        el: '#app'
    })
</script>

在子组件的props中可以接收父组件传来的content属性,并且在content中可以定义type限制content属性类型,通过required限制是否必须传值,通过default可以指定当没有传值时的默认的参数值,通过validator可以自定义一些参数校验的方法,并且return出去,当return返回false时,就说明没有通过校验,页面将会报错。

猜你喜欢

转载自blog.csdn.net/qq_33866063/article/details/89633942