vue -------组件

作者: 放飞吧自我 | 来源:发表于2018-01-30 21:51 被阅读17次

全局注册

//注册
Vue.component("MyComponent",{
        template:"<h1>我是全局注册的mycomponent</h1> 数据是{{mymessage}}",
        data:function () {
            return {
                mymessage:"我是全局组件里的数据"
            }
        }
    })

创建实例

// 创建根实例
new Vue({
  el: '#example'
})

html

<div id="example">
  <my-component></my-component>
</div>

局部注册

var HelloWorld={
        template:"<h1>我是helloworld组件{{message}}<button @click='changemessage'>点击我切换组件</button></h1>",
        //结论:组件里的data一定要用function方式,不让会传址
        data:function () {
            return obj;
        },
        methods:{
            changemessage:function () {
                this.message="我是测试数据2"
            }
        }
    }
    //局部定义组件
var Child={
    template:"<h1>我是局部注册组件</h1>",
    components:{
        HelloWorld:HelloWorld
    }
}

实例化

new Vue({
        el:"#app",
        data:{
            message:"wishing",
            judge:false
        },
        components:{
            MyComponent:Child,
            helloworld:HelloWorld
        }
    })

组件的传参

通过属性传递
    <my-component age="hell111o"></my-component>
接收属性通过
 props:['username','height','color']

动态props通过v-bind:属性,来进行绑定

Prop验证(注意必须是开发版vue)

我们可以为组件的 prop 指定验证规则。如果传入的数据不符合要求,Vue 会发出警告,生产版本删除了警告

props:{
    data: {
        type: [Number,String],
        default: 100,
        required:true
    },
},

组件引入方式

1.直接引入

   模板中使用标签<MyComponent></MyComponent>或者是<my-component></my-component>

2.通过js引入

自定义事件($emit第二个参数传递值)

<div id="myapp">
{{ DadData }}
<my-component v-on:test="dadmytest"></my-component>
</div>

</body>
<script>
    var myConponent = {
        template:"<h1 @click='sub'>我是组件里的内容</h1>",
        data:function () {
            return {
                message:"i am message"
            }

        },
        methods: {
            sub:function () {
                console.log("hello world")
                this.$emit("test")
            }
        }
    }

    var vm = new Vue({
        el:"#myapp",
        components:{
            "my-component":myConponent
        },
        data:{
            DadData:"我是父级的数据"
        },
        methods:{
            dadmytest:function () {
                console.log(2222)
            }
        }
    })

</script>

相关文章

网友评论

    本文标题:vue -------组件

    本文链接:https://www.haomeiwen.com/subject/qhchzxtx.html