Vue 父组件和子组件之间那点儿破事儿
2019-03-18 本文已影响0人
GA_
- 父组件—传值—>子组件
1、子组件绑定父组件的数据
v-bind:post="post"
2、子组件用props接收
props: ['post'],
- 父组件—监听—>子组件
1、监听(父)
v-on:enlarge-text=“执行的事件"
2、发送(子)
v-on:click="$emit('enlarge-text')"
具体代码实现
- postDemo.js
import Vue from 'vue'
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>
})
- vue_global_api.vue
<template>
<div id="vue_global_api">
<div id="components-demo">
<!--
v-bind:key 不传有警告
v-bind:post post是组件内接收的参数名
-->
<!-- <blog-post v-for="post in posts" v-bind:post="post" v-bind:key="post.id" v-on:enlarge-text="onEnlargeText"></blog-post> -->
<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 :style="{ fontSize: postFontSize + 'em' }">
<blog-post v-for="post in posts" v-bind:key="post.id" v-bind:post="post" v-on:enlarge-text="postFontSizeAction"></blog-post>
</div>
</div>
</div>
</template>
<script>
import {
postDemo
} from '../js/postDemo.js'
export default {
el: 'vue_global_api',
data() {
return {
posts: [{
id: 1,
title: 'My journey with Vue'
},
{
id: 2,
title: 'Blogging with Vue'
},
{
id: 3,
title: 'Why Vue is so fun'
}
],
data: {
title: "this.title",
message: "this.message"
},
postFontSize: 1
}
},
methods: {
postFontSizeAction() {
this.postFontSize += 0.1
}
}
}
</script>
<style>
</style>