美文网首页Vue从0到死亡前端Vue专辑Vue.js
Vue 父组件和子组件之间那点儿破事儿

Vue 父组件和子组件之间那点儿破事儿

作者: GA_ | 来源:发表于2019-03-18 16:35 被阅读0次
    • 父组件—传值—>子组件
        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>
    

    相关文章

      网友评论

        本文标题:Vue 父组件和子组件之间那点儿破事儿

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