vue - 组件通信

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

  • $on()——监听事件。
  • $emit()——把事件沿着作用域链向上派送。(触发事件)
  • $dispatch()——派发事件,事件沿着父链冒泡。
  • $broadcast()——广播事件,事件向下传导给所有的后代。

父子组件之间的访问

  • 父组件访问子组件:使用$children或$refs
  • 子组件访问父组件:使用$parent
  • 子组件访问根组件:使用$root

父组件 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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 组件通信各种情况总结VUE是以数据驱动的MVVM框架,又是模块化开发,所以各个组件间的通信传递数据非常重要,在项目...
    流年_338f阅读 591评论 0 2
  • vue 组件通信分为父组件与子组件通信、子组件与父组件通信、非父子关系组件通信三种 第一种大家都知道用props,...
    lyn911阅读 2,220评论 0 0
  • Vue 实例 属性和方法 每个 Vue 实例都会代理其 data 对象里所有的属性:var data = { a:...
    云之外阅读 2,244评论 0 6
  • 1) 父组件给子组件传值 利用Vue的组件机制,父亲组件通过 v-bind指令给子组件绑定一个属性,属性值为父组件...
    小枫学幽默阅读 565评论 1 7
  • 又到了忙碌的时候,整理试卷、写小结、做材料、回邮件,今天上午不知要忙成哪样。下午开会的时候,把时间利用起来。还有儿...
    mycarolrong阅读 212评论 0 0