vue中的组件

组件可以扩展HTML元素,封装可重用的代码,组件分为全局和局部

全局:

Vue.component('my-component',{
        template:`
            <div>
            <h1>{{msg}}</h1>
                <ul>
                    <li>hello</li>
                    <li>nihao</li>
                </ul>
            <button v-on:click="alt">按钮</button>
            </div>
        `,
        data:function(){
            return{
                msg:'heilop'
            }
        },
        methods:{
            alt:function(){
                alert(11111)
            }
        }
    })

局部:

new Vue({
        el:'#itany',
        components:{
            'my-component':{
                template:`
                    <ul>
                        <li>sdsadjosap</li>
                        <li>dbsjakdhsajk</li>
                    </ul>
                `
            }
        }
    })

组件之间的传值

父传子 用属性传 props:[ ]
子传父 用事件传

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="itany">
    <my-components></my-components>
</div>
<script src="dist/vue.js"></script>
<script>
    Vue.component("my-components",{
        template:`
            <div>
                <h1>我是父亲</h1>
                <my-child v-bind:age="arr"></my-child>
            </div>
        `,
        data:function(){
            return{
                arr:[1,2,3,5]
            }
        }
    }),
    Vue.component("my-child",{
        props:['age'],
        template:`
            <div>
                <ul>
                    <li v-for="val in age">{{val}}</li>
                </ul>
            </div>
        `
    })
    new Vue({
        el:'#itany',
    })
</script>
</body>
</html>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容