vue - 组件通信

2017-07-20  本文已影响83人  开车去环游世界

每个Vue实例都是一个事件触发器:

父子组件之间的访问

父组件 App.vue:

<template>
    <div id="app">
        <child message="hello" ref="hello"></child>
        <child v-bind:message="msg" v-on:listenToChildEvent="showMsgFromChild"></child>

        <br/>
        <button @click="showChildComponentData">显示子组件的数据</button>
    </div>
</template>

<script>
import child from './components/Child'

export default {
    name: 'app',
    data() {
        return {
            msg: "Hello, child!"
        }
    },
    methods: {
        showMsgFromChild( data ) {
            alert( data );
        },

        showChildComponentData() {
            console.log( this.$refs.hello );
            alert( this.$refs.hello.msg );
            alert( this.$refs.hello.message );
        }
    },
    components: {
        child
    }
}
</script>

<style>
#app {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
}
</style>

子组件 Child.vue:

<template>
    <div>
        <h2>child子组件部份</h2>
        <p>{{message}}</p>
        <button type="button" name="button" v-on:click="sendMsgToParent">向父组件传值</button>

        <br>
        <button type="button" name="button" @click="showParentMsg">显示父组件信息</button>
    </div>
</template>

<script>
  export default {
    data() {
        return {
            msg: "在父组件(App.vue)通过 $ref 调用"
        }
    },
    props: [ 'message' ],
    methods: {
        sendMsgToParent() {
            this.$emit( "listenToChildEvent", "this message is from child!" );
        },

        showParentMsg() {
            console.log( this.$parent );
            alert( this.$parent.msg );
        }
    }
  }
</script>
<style>

</style>
上一篇下一篇

猜你喜欢

热点阅读