組件參數校驗與非props特性

父組件傳遞content="hello world",子組件有權對其進行約束,或者說校驗

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="./vue.js"></script>
    <!-- <script src="http://cdn.staticfile.org/vue/2.6.10/vue.common.dev.js"></script> -->
</head>
<body>
<div id="root">
    //這依然是字符串 <br>
    <child1 content="1"></child1>

    //用:的方式,引號內的是js表達式,如果是數字,它就是數字類型 <br>
    <child2 :nums="2"></child2>

    <child3 other="123456"></child3>

    <child4 isProps="is false"></child4>
</div>
<script type="text/javascript">
    Vue.component("child1", {
        /*//如果要進行約束,就不要像這樣是數組,改爲對象咯
        props: ["content"],*/

        props: {
            content: Number //子組件接收的必須是數字類型
        },
        template: "<div>{{content}}</div>"
    });

    Vue.component("child2", {
        /*//如果要進行約束,就不要像這樣是數組,改爲對象咯
        props: ["content"],*/

        props: {
            nums: [Number, String] //子組件接收的必須是字符串類型或數字類型
        },
        template: "<div>{{nums}}</div>"
    });

    Vue.component("child3", {
        props: {
            //當然還可以是對象
            other: {
                type: String, //必須是字符串
                required: false, //非必須有
                default: "default value", //沒有則給默認值
                validator: function(value) {
                    return (value.length > 5) //要求傳入的內容長度必須大於5
                }
            }
        },
        template: "<div>{{other}}</div>"
    });

    Vue.component("child4", {
        //像這樣沒有props,則父組件向當前子組件傳遞的屬性也使用不了
        template: "<div>{{isProps}}</div>"
    });

    var vm = new Vue({
        el: "#root"
    });
</script>
</body>
</html>

雖然規定只能傳數字,但傳了字符串還是能顯示,但控制檯會警告:
組件參數校驗與非props特性
如果子組件中使用了父組件傳過來的數據,而不用props,則用不到這個屬性,會報錯(不接收,怎能使用):
組件參數校驗與非props特性

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章