Vue

Vue 组件 / 创建

2018-03-19  本文已影响0人  羊烊羴
全局组件
Vue.component("tem",{
    template:`
        <div>
            <h3>全局组件</h3>
        </div>
        `
})
局部组件
<body>
<div id="app">
    <child></child>
</div>

<template id="child">
    <div>
        <p>this's chlidTem</p>
    </div>
</template>
<script>
    new Vue({
        components:{
            "child":{
                template:"#child"
            }
        }
    }).$mount("#app")
</script>
</body>
动态组件

通过所使用保留的<component>元素,动态的绑定到它的is特性,我们可以让多个组件可以使用同一个挂载点,并且动态切换

<body>
<div id="app">
    <div>
        <input type="button" 
               v-for="item in inputs"  
               :value="item.index" :index="item.index" 
               @click="showTem($event)">
    </div>
    <component :is="show"></component>
</div>
<script>
    new Vue({
        data:{
            inputs:{
                first:{
                    index:"first"
                },
                second:{
                    index:"second"
                },
                third:{
                    index:"third"
                }
            },
            show:"first"
        },
        methods:{
            showTem(e){
                this.show=e.target.getAttribute("index");
            }
        },
        components:{
            "first":{
                template: `
                    <div>this's first</div>
                `
            },
            "second":{
                template:`
                    <div>this's second</div>
                `
            },
            "third":{
                template:`
                   <div>this's third</div>
                `
            }
        }
    }).$mount("#app")
//由上我们可以看出,实际上动态组件的本质就是通过:is来控制组件的显示/隐藏,当然除了通过不同的按钮来控制,也可以通过单个按钮的click方法为show赋不同的值来改变模板的显示/隐藏
</script>
</body>
上一篇下一篇

猜你喜欢

热点阅读