zoukankan      html  css  js  c++  java
  • Vue2.0 【第二季】第7节 Component 组件 props 属性设置

    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']
    		}
    	}
    })
    

    浏览器效果:

    同样可以实现以上效果。

    Keep moving on!
  • 相关阅读:
    函数节流throttle和防抖debounce
    用RecyclerView做一个小清新的Gallery效果
    JavaScript之三
    vue介绍
    water
    吴裕雄--天生自然 R语言开发学习:基本统计分析
    吴裕雄--天生自然 R语言开发学习:基本图形(续三)
    吴裕雄--天生自然 R语言开发学习:基本图形(续二)
    吴裕雄--天生自然 R语言开发学习:基本图形(续一)
    吴裕雄--天生自然 R语言开发学习:基本图形
  • 原文地址:https://www.cnblogs.com/Elva3zora/p/12496617.html
Copyright © 2011-2022 走看看