组件基础
组件是可复用的Vue实例,且带有一个名字:在这个例子中<button-counter>
为一个组件。可以通过new Vue创建的Vue根实例中,把这个组件最为自定义元素来使用。
<div id="blog-posts-events-demo" class="demo">
<div :style="{ fontSize: postFontSize + 'em' }">
<blog-post v-for="post in posts"
v-bind:key="post.id"
v-bind:post="post"
v-on:enlarge-text="postFontSize += 0.1"></blog-post>
</div>
</div>
<script>
Vue.component('blog-post', {
props: ['post'],
template: '\
<div class="blog-post">\
<h3>{{ post.title }}</h3>\
<button v-on:click="$emit(\'enlarge-text\')">\
Enlarge text\
</button>\
<div v-html="post.content"></div>\
</div>\
'
})
new Vue({
el: '#blog-posts-events-demo',
data: {
posts: [
{ id: 1, title: 'My journey with Vue', content: '...content...' },
{ id: 2, title: 'Blogging with Vue', content: '...content...' },
{ id: 3, title: 'Why Vue is so fun', content: '...content...' }
],
postFontSize: 1
}
})
</script>
实例2:
<body>
<div id="app">
<button-counter title="title1: " @clicknow="clicknow"></button-counter>
<button-counter title="title2: " @clicknow="clicknow"></button-counter>
</div>
</body>
<script>
Vue.component('button-counter', {
props:['title'],
data: function(){
return {
count: 0
}
},
template: '<div><h1>hhhhh</h1><button v-on:click="clickfun">{{title}} You clicked me {{count}} times.</button><slot></slot></div>',
methods:{
clickfun: function(){
this.count ++
this.$emit('clicknow', this.count);
}
}
})
var vm = new Vue({
el: "#app",
data:{
},
methods:{
clicknow: function(e){
console.log(e)
}
}
})
</script>