console
Vue.component('button-counter', {
props: ['title'], // 用来向内部子组件传递数据
data: function () { // 每个组件实例内部data各自独立
return {
count: 0
}
},
template: '<div><h1>hi...</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);
}
}
})
Vue.component('blog-post1', {
props: ['title'],
template: '<h3>{{ title }}</h3>'
})
Vue.component('blog-post2', {
props: ['post'],
template: `
<div class="blog-post">
<h3>{{ post.title }}</h3>
<div v-html="post.content"></div>
</div>
`
})
Vue.component('blog-post3', {
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>
`
})
var vm = new Vue({
el : "#app",
data : {
posts: [
{ id: 1, title: 'My journey with Vue' },
{ id: 2, title: 'Blogging with Vue' },
{ id: 3, title: 'Why Vue is so fun' }
],
postFontSize: 1
},
methods:{
clicknow : function (e) {
console.log(e);
}
},
components:{
test : {
template:"<h2>这是一个局部组件</h2>"
}
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<button-counter title="title1 : " @clicknow="clicknow">
<h2>hi...h2</h2>
</button-counter>
<button-counter title="title2 : "></button-counter>
<br/><br/>
<test></test><br/><br/>
<label>props传值:</label><br/>
<blog-post1
v-for="post in posts"
v-bind:key="post.id"
v-bind:title="post.title"
></blog-post1><br/>
<label>props传对象:</label><br/>
<blog-post2
v-for="post in posts"
v-bind:key="post.id"
v-bind:post="post"
></blog-post2><br/>
<label>监听子组件事件:</label><br/>
<div :style="{ fontSize: postFontSize + 'em' }">
<blog-post3
v-for="post in posts"
v-bind:key="post.id"
v-bind:post="post"
v-on:enlarge-text="postFontSize += 0.1"
></blog-post3>
</div>
</div>
body,td,th {color: #DDDDDD}