组件基础(参数校验和动态组件、v-once)—Vue学习笔记

最最最后一点关于组件传值的问题。

提醒:本篇内容请使用Vue.js开发版!(附带完成的警告和提示)

1.组件的参数校验

父组件向子组件传值,子组件可以决定传值的一些限制。

比如,子组件指向接收String类型的值,在传递时props应该这样写:


<body>
<div id="app">
<hello content='hi boy'>
</hello>
</div>
</body>

<script>
    Vue.component("hello",{
        props:{
            content:String//限制接收值的类型为字符串
            }
        },
        template:'<div>{{content}}</div>'
    })

    var app=new Vue({
        el:'#app'
    })
</script>

PS:这里我们通过content进行传值。

<body>
    <div id="app">
        <hello content='hi boy'>        
        </hello>
    </div>
</body>

直接子组件里使用 变量名=‘值’ 子组件接收到的时字符串。

使用 :变量名=‘数字’ 子组件可接收Number

<div id="app">
    <hello :content='123'>        
    </hello>
</div>

关于参数校验,我们可以通过

直接限制类型(content:String)

数组形式(content:[String,Number])

类content:{

  typy:String,

  required:true,//规定是否为必传参数

  default:'默认值',//当为传入值时,默认为**

  validator:function(value){//自定义校验器

    return (value.length>5)//当大于5时返回true

  }

}

例子:

<body>
    <div id="app">
        <hello content='hi boy'>        
        </hello>
    </div>
</body>
<script>
    Vue.component("hello",{
        props:{
            content:{
                type:String,
                required:false,//必传
                default:'default value'//默认值
                validator:function(value){
                    return (value.length>5)
                }//通过校验器校验,要求长度大于五(满足条件返回true)
            }
        },
        template:'<div>{{content}}</div>'
    })

    var app=new Vue({
        el:'#app'
    })
</script>

2.动态组件

通过  <component :is='组件名'></component>  来实现组件的动态切换。

例子:我们现在有两个组件chind-one和child-two通过按钮点击决定显示哪一个组件。(显示用v-if)

<body>
    <div id="app">
        <child-one v-if="type==='child-one'"></child-one>
        <child-two v-if="type==='child-two'"></child-two>

        <button @click="handleClick">DoIt</button>
    </div>
</body>
<script>
    Vue.component("child-one",{
        template:'<div>child-one</div>'
    })

    Vue.component("child-two",{
        template:'<div>child-two</div>'
    })

    var app=new Vue({
        el:'#app',
        data:{
            type:'child-one'
        },
        methods:{
            handleClick:function(){
            this.type=this.type==='child-one'?'child-two':'child-one'
            }
        }
    })
</script>

这样我们就是先了点击按钮显示不同组件(三元表达式)

当然是一种静态的方法,现在改为动态,只需一句:

<div id="app">
        <component :is="type"></component>
        <button @click="handleClick">DoIt</button>
    </div>

这里的type就是我们需要显示的组件名。

3.v-once指令

正如上面的例子,我们向实现两个组件的来回切换显示,Vue底层会为我们进行大量的工作区插入组件,删除组件。但是平凡的操作时很消耗性能的。

这时候,我们就需要用到v-once

Vue.component("child-one",{
        template:'<div v-once>child-one</div>'//模板中添加v-once
    })

这样当组件第一次生成时会存放到内存之中。避免重复创建,节省性能。

好了,这些时官方说明文档很少提到的(可能是我大意没看到),所以把它写下来。

如果要学习Vue.js的话还是推荐看一下官方API。

最近我也写了一个图片调用的Api,大约3万张左右的图片,包括风景大片,美女图片,动漫卡通,时尚炫酷,文字控以及小清新。

调用方法非常简单,返回参数无需过滤即可使用。

这里是链接YoungAm-图片Api

手机端还有一点小bau不影响使用。

不过,禁止恶意调用。

嘿嘿!

原文地址:https://www.cnblogs.com/tcxq/p/10334353.html