Vue2.0 的漫长学习ing-2-7

Component 组件props 属性设置

  props选项就是设置和获取标签上的属性值的,例如我们有一个自定义的组件<xiaofan></xiaofan>,这时我们想给他加个标签属性写成<panda here=’sichuan’></panda> 意思就是xiaofan来自sichuan,当然这里的sichuan可以换成任何值。定义属性的选项是props。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script type="text/javascript" src="../assets/js/vue.js"></script>
    <title>component-2</title>
</head>
<body>
    <h1>component-2</h1>
    <hr>
    <div id="app">
      <xiaofan here="sichuan"></xiaofan>
    </div>
 
    <script type="text/javascript">
        var app=new Vue({
            el:'#app',
            components:{
                "xiaofan":{
                    template:`<div style="color:red;">xiaofan from {{ here }}.</div>`,
                    props:['here']
                }
            }
        })
    </script>
</body>
</html>

  注意:上面代可以理解为:我们在一个标签里面加了一个方法here,方法的值是sichuan,同时我们局部自定义了一个组件xiaofan,组件里面有一个pros选项,而这个pros选项后面跟的是数组,在上面例子中我们将pros的值指向了here,而我们又在标签内定义了其值为sichuan,所以我们调用{{ here }} ,最终会获得 sichuan这个值。

属性中带’-‘的处理方式

  在外面写属性时,在html中有许多都是带有"-"的,比如background-color,而当我在props中写的时候是不允许这样,我们必须写成backgroundColor,也就是"-"连接两个单词,而我们需要写成一个单词,第二个单词首字母大写,多个单词组合的类似。

在构造器里向组件中传值

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

html:

<xiaofan :here = "msg"> </xiaofan>

js:

var app = new Vue({
       el:"#app",
       data:{
         msg:"sichuan"
    },
      compontens:{
        'xiaofan':{
            template:`<div style = "color:red;"> xiaofan from {{msg}} </div>,
            props:['here']
            } 
        }    
 })

猜你喜欢

转载自www.cnblogs.com/xiaofandegeng/p/9029039.html