程序之路

this.$refs与this.$emit()

2021-06-16  本文已影响0人  深吸一口气

this.$refs

父组件向子组件通信,可以调用子组件里的属性和方法

示例

<template>
  <child ref="msg" />
</template>

<script>
  import child from "./child.vue";
  export default {
    name: "parent",
    components: {child},
    mounted(){
      // 通过ref定位组件并调用组件的方法
      this.$refs.msg.setMessage("我是子组件")
    }
  }
</script>
<template>
  <h1>{{msg}}</h1>
</template>

<script>
  export default {
    name: "",
    data(){
      return {
        msg: ""
      }
    },
    methods: {
      setMessage(msg){
        this.msg = msg;
      }
    }
  }
</script>

this.$emit()

子组件向父组件通信

使用方式

vm.$emit( event, arg )

示例

<template>
  <!-- 通过绑定子组件定义的getMessage事件获取信息 -->
  <child @getMessage="showMessage" />
</template>

<script>
  import child from "./child.vue";
  export default {
    name: "parent",
    components: {child},
    methods: {
      showMessage(msg){
        console.log(msg)
      }
    }
  }
</script>
<template>
  <h1>{{msg}}</h1>
</template>

<script>
  export default {
    name: "",
    data(){
      return {
        msg: "hello"
      }
    },
    methods: {
      getMessage(){
        this.$emit("getMessage", this.msg)
      }
    }
  }
</script>
上一篇下一篇

猜你喜欢

热点阅读