组件之间的通信

来源:互联网 发布:数据防泄密方案 编辑:程序博客网 时间:2024/05/18 01:57

准备阶段

先写子组件componentA.vue:

<template>  <div class="hello">    <h1>{{ msg }}</h1>  </div></template><script>  export default {    name : 'componentA',    data : function() {      return {        msg: 'component a'      }    }  }</script><style scoped>  h1, h2 {    font-weight: normal;    color: #42b983;  }</style>

在父组件(App.vue)中导入上面的组件:

<template>  <div id="app">    <h1>{{ title }}</h1>    <component-a></component-a>   <!--将驼峰式的写法要写成左边那样-->    ....  </div></template><script>  import componentA from './components/componentA.vue' //*  export default {    name: 'hello',    components: { componentA },  //*    data: function() {      return {        ....      }    },    methods: {        .....    }  }</script><style>    ....</style>

那么子组件如何收到父组件的信息呢?

父组件里面:

<component-a fathertell="hello, my son"></component-a>

子组件里面:要加上props这个属性,并且里面的变量名要表示成字符串的形式,并且在子组件里面可以访问到这个变量

  export default {    name : 'componentA',    props: ['fathertell'],    data : function() {      return {        msg: 'hello from component a'      }    }  }

子组件向父组件传递参数的情况

父组件里:父组件中使用v-on绑定自定义事件,如这样v-on:child-tell="listenToMySon",其中”child-tell“就是我的自定义事件,而”listenToMySon“就是事件处理函数

<p>Child tells: {{ childWords }}</p><component-a fathertell="hello, my son" v-on:child-tell="listenToMySon"></component-a>
  export default {    name: 'hello',    components: { componentA },    data: function() {      return {        ...        childWords : ''    //这个与显示的{{ childWords }}对应      }    },    methods: {      listenToMySon : function(msg) {   //自定义事件的事件处理函数          this.childWords = msg;      }    }  }

子组件里:子组件当然是要触发这个自定义事件了,在这里我让点击按钮时触发

<button @click="onClickMe">ComponentA say</button>
methods: {  onClickMe: function() {    this.$emit('child-tell', this.msg);  //参数:自定义事件 传给父组件的参数(这个与父组件的事件处理                                    //函数的参数对应)  }}