首页 > 其他 > 详细

Vue2.0 【第二季】第7节 Component 组件 props 属性设置

时间:2020-03-15 12:50:39      阅读:58      评论:0      收藏:0      [点我收藏+]

Vue2.0 【第二季】第7节 Component 组件 props 属性设置


第7节 Component 组件 props 属性设置

props选项就是设置和获取标签上的属性值的,例如我们有一个自定义的组件,这时我们想给他加个标签属性写成 意思就是熊猫来自中国,当然这里的China可以换成任何值。定义属性的选项是props

一、定义属性并获取属性值

定义属性我们需要用props选项,加上数组形式的属性名称,例如:props:[‘here’]。在组件的模板里读出属性值只需要用插值的形式,例如{{ here }}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>component-2</title>
    <script type="text/javascript" src="../assets/js/vue.js"></script>
</head>
    <body>
        <h1>component-2</h1>
        <hr>
        <div id="app">
            <monkey here="China"></monkey>
        </div>

        <script type="text/javascript">
            var app = new Vue({
                el:'#app',
                components:{   //可以定义多个
                    "monkey":{  //这块必须是字符串,不然相当于没定义
                        template:'<div style="color:green">Monkey is from {{here}}.</div>',
                        props:['here']
                    }
                }
            })
        </script>
    </body>
</html>

浏览器效果:
技术分享图片

上面的代码定义了monkey的组件,并用props设置了here的属性值,在here属性值里传递了China给组件。 最后输出的结果是绿色字体的Monkey is from China.

二、属性中带‘ - ‘的处理方式

我们在写属性时经常会加入’-‘来进行分词,比如:<monkey from-here="China"></monkey>,那这时我们在props里如果写成props:[‘form-here’]是错误的,我们必须用小驼峰式写法props:[‘formHere’]。(大驼峰:FromHere)

html文件:

<monkey from-here="China"></monkey>

js文件:

var app = new Vue({
    el:'#app',
    components:{   //可以定义多个
        "monkey":{  //这块必须是字符串,不然相当于没定义
            template:'<div style="color:green">Monkey is from {{fromHere}}.</div>',
            props:['fromHere']
        }
    }
})

PS:因为这里有坑,所以还是少用-为好。

三、在构造器里向组件中传值

把构造器中data的值传递给组件,我们只要进行绑定就可以了。就是我们第一季学的v-bind:xxx

html文件:

<monkey v-bind:here="message"></monkey>或者简写:<monkey :here="message"></monkey>

js代码:

var app = new Vue({
    el:'#app',
    data:{
        message:'China'
    },
    components:{   //可以定义多个
        "monkey":{  //这块必须是字符串,不然相当于没定义
            template:'<div style="color:green">Monkey is from {{here}}.</div>',
            props:['here']
        }
    }
})

浏览器效果:
技术分享图片

同样可以实现以上效果。

Vue2.0 【第二季】第7节 Component 组件 props 属性设置

原文:https://www.cnblogs.com/Elva3zora/p/12496617.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!