极客

Vue父子组件通信

2019-02-20  本文已影响0人  极客传

1.子组件的 props 属性
通过子组件的 props 属性,可以将父组件上的数据传入子组件,如下例中的 deliverNum。 另外,若 props 传递的数据是一个引用类型,在子组件中修改这个数据时,会影响到父组件的状态。因此通过子组件的 props 属性,可实现父子组件数据的双向传递。

注意在 JavaScript 中对象和数组是通过引用传入的,所以对于一个数组或对象类型的 prop 来说,在子组件中改变这个对象或数组本身将会影响到父组件的状态。

子组件 Counter.vue 内容:

<template>
<div> <!--注意组件必须要有一个根元素,如此处的div标签-->
    <button v-on:click="increase">+</button>
    <button v-on:click="decrease">-</button>
    <p> <span>父传递到子组件的值{{deliverNum}}</span> </p>
    <p> <span>子组件值{{num}}</span> </p>
</div>
</template>
<script>
    export default{
        props: ["deliverNum"], //注意此处的deliverNum即父组件传入的deliverNum,要写相同
        data() {
            return {
                num: 0
            }
        },
        methods: {
            increase: function () {
                this.$emit("incre");
            },
            decrease: function () {
                this.$emit("decre");
            }
        }
    }
</script>

.
父组件 Hello.vue 内容:

<template>
  <div class="hello">
        <h1>{{msg}}</h1>
        <Counter v-bind:deliverNum="parentNum" v-on:incre="increment" v-on:decre="decrement"></Counter>  <!--动态传值,加上v-bind-->
        <p>父组件的值{{parentNum}}</p>
  </div>
</template>
<script>
    import Counter from "./Counter.vue"
    export default {
        name: "hello",
        data () {
            return {
                parentNum: 10,
                msg: "welcome to your vue.js app"
            }
        },
        components: {
            Counter
        },
        methods: {
            increment: function () {
                this.parentNum++;
            },
            decrement: function() {
                this.parentNum--;
            }
        }
    }
</script>
  1. this.$emit() 触发父组件方法

上例中,当点击 + 时,首先执行子组件内的方法 increase ,该方法会触发父组件的 incre 事件,进而执行父组件中的 increment 方法,令 parentNum++ ,同时 deliverNum="parentNum" 又将 parentNum 传入子组件进行更新。
另外,this.$emit() 方法可以传参,子组件传值,父组件方法被触发时,会接收到传过来的值。因此,this.$emit() 既可实现子组件内触发父组件方法,又可实现子向父传值。

.
3.this.$refs 触发子组件内方法

父子组件内容如下,ref 为子组件指定了一个引用 ID ,通过 this.$refs.child1 获取到的是该子组件的 vue 实例。 this.$refs.child1.showName() 即可令子组件内的 showName() 方法执行。

<!--父组件-->
<div id="parent">
  <children ref="child1"></children>
</div>

<script>
import children from 'components/children/children.vue'
  export default {
    data(){
      return {
      }
    },
    components: {      
      'children': children
    },
    created(){
      console.log(this.$refs.child1) // 返回一个vue对象,所以可以直接调用其方法
      this.$refs.child1.showName() // 调用子组件内的showName()方法
    }
  }
</script>

子组件内容如下:

<--!子组件-->
<template>
  <div>
    <p>这是子组件</p>
  </div>
</template>

<script>
  export default {
    data(){
      return {
          
      }
    },
    methods:{
      showName () {
        alert('river jean')
      }
    }
  }
</script>
上一篇 下一篇

猜你喜欢

热点阅读