【问题标题】:Calling function inside child component without an event?在没有事件的情况下调用子组件内的函数?
【发布时间】:2021-08-13 14:43:43
【问题描述】:

当前正在尝试使用属于父级的方法

   <p class="message-date text-center">
       {{ $emit('format_date_day_month_year_time', message.date) }}
   </p>

但是我得到了错误。

Converting circular structure to JSON
    --> starting at object with constructor 'Object'

如何在不依赖事件的子组件中调用函数?我很抱歉问了这么简单的问题,但我在谷歌上找到的所有东西都是使用 $emit 和一个事件。

【问题讨论】:

标签: vue.js vuejs2 vue-component


【解决方案1】:

$emit 被设计为仅在当前 vue 实例上触发事件。因此,无法通过这种方式从其他组件接收数据。

对于您的情况,我建议您使用Mixins,尤其是如果您需要在多个 vue 组件中使用某些功能。

或者,让子组件通过$emit调用父组件,然后通过prop从父组件接收结果。

您的代码可能如下所示:

子组件

<template>
  <p class="message-date text-center">
    {{ date }}
  </p>
</template>

<script>
export default {
  name: 'Child',
  props: {
    date: String,
  },
  mounted() {
    this.$emit("format-date", message.date);
  },
}
</script>

父组件

<template>
  <Child :date="childDate" @format-date="formatChildDate" />
</template>

<script>
import Child from '@/components/Child';

export default {
  components: {
    Child,
  },
  data: () => ({
    childDate: '',
  }),
  methods: {
    formatChildDate(date) {
      this.childDate = this.formatDateDayMonthYearTime(date)
    },
    formatDateDayMonthYearTime(date) {
      //return  the formatted date
    },
  },
}
</script>

【讨论】:

    【解决方案2】:

    使用 $emit 您可以调用 Parent 可以监听的函数。

    你在哪里使用它,我会建议函数的计算属性。

    但回到你的问题,这里是一个发射和倾听的例子。

    //Parent 
    <template>
    <MyComponent @childFunction="doSomethingInParent($event)"/>
    </template>
    
    //Child
    <template>
    <button @click="emitStuff">
    </template>
    .....
    methods:{
    emitStuff(){
    this.$emit(childFunction, somedata)
    }
    

    通过事件,您可以将数据信息提供给父组件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-17
      相关资源
      最近更新 更多