vue组件

组件:页面中的任何一个部分都是组件,它由html、css、js组成。组件继承于实例,它就是一个小型的vue实例,vue中有什么,组件中就有什么,稍有变异,它的配置项中data不是一个对象,而是一个函数。

组件的嵌套:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>组件嵌套</title>
    <script src="./js/vue.js"></script>
    <style>
        .father {
            width: 300px;
            height: 300px;
            background-color: red;
        }

        .son {
            width: 200px;
            height: 200px;
            background-color: greenyellow;
        }
    </style>
</head>

<body>
    <div id="app">
        <father></father>
    </div>
    <template id="father">
        <div class="father">
            父组件<son></son>
        </div>
    </template>
    <template id="son">
        <div class="son">
            子组件
        </div>
    </template>
    <script>
     //全局组件的嵌套 // Vue.component("father",{ // template:"#father" // }) // Vue.component("son",{ // template:"#son" // }) new Vue({ el:"#app",
       //局部组价的嵌套 components:{
"father":{ template:"#father", components:{ "son":{ template:"#son" } } } } }) </script> </body> </html>

 

组件传值:

  父传子:props属性

    1、在子组件中,props用来接收自定义属性的值,这个值可以在该组件中使用。

    2、这个值只能拿来用,不能去修改。

    3、自定义属性的值为变量或表达式时,在属性前加  :

    4、接收方式:数组----props:[自定义属性],对象----props:{自定义属性:{type:  default:  required:true}}

        type:限制外部数据的类型

        default:默认值,当父组件没有给子组件传值时使用默认值

        required:true----表示当前属性是必传的值(和default二选一)  

  子传父:$emit()----触发本组件身上的自定义方法

    给当前子组件绑定一个自定义方法,值为接收参数的函数(这个函数不带括号),在子组件内部通过this.$emit()来调用自定义方法。

    $emit("hehe",100)

      "hehe"----自定义事件名

      100----参数

  非父子:

    亲兄弟之间----子组件控制父组件的显示和隐藏

    远房亲戚----Eventbus(事件总线)

        let bus=new Vue();----创建一个空实例,bus.$on()----在实例上注册事件,bus.$emit()----触发实例上$on注册的事件

posted @ 2019-08-14 19:57  吴小明-  阅读(176)  评论(0编辑  收藏  举报