Vue.js 在没有事件的子组件内调用函数?

Vue.js 在没有事件的子组件内调用函数?,vue.js,vuejs2,vue-component,Vue.js,Vuejs2,Vue Component,当前正在尝试使用属于父级的方法 <p class="message-date text-center"> {{ $emit('format_date_day_month_year_time', message.date) }} </p> 如何在不依赖事件的子组件内调用函数?我很抱歉问这么简单的问题,但我在google上找到的所有东西都使用$emit并使用事件。使用$emit,您可以调用一个父级可以侦听的函数 在您使用它的地方

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

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

如何在不依赖事件的子组件内调用函数?我很抱歉问这么简单的问题,但我在google上找到的所有东西都使用$emit并使用事件。

使用$emit,您可以调用一个父级可以侦听的函数

在您使用它的地方,我建议使用函数的计算属性

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

//Parent 
<template>
<MyComponent @childFunction="doSomethingInParent($event)"/>
</template>

//Child
<template>
<button @click="emitStuff">
</template>
.....
methods:{
emitStuff(){
this.$emit(childFunction, somedata)
}
//父对象
//孩子
.....
方法:{
(){
此.$emit(childFunction,somedata)
}

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

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

对于您的情况,我建议使用,特别是当您需要在多个vue组件中使用某些函数时

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

您的代码可能如下所示:

子组件


{{date}}

导出默认值{ 姓名:'儿童', 道具:{ 日期:String, }, 安装的(){ 此.$emit(“格式日期”,message.date); }, }
父组件


从“@/components/Child”导入子项;
导出默认值{
组成部分:{
小孩
},
数据:()=>({
子女日期:'',
}),
方法:{
formatChildDate(日期){
this.childDate=this.formatDateDayMonthYearTime(日期)
},
formatDateDayMonthYearTime(日期){
//返回格式化的日期
},
},
}

我快速搜索并找到了此链接。它推荐了一种我也会推荐的技术,将道具从父对象传递给子对象,并观察子对象中的道具以触发函数调用。
//Parent 
<template>
<MyComponent @childFunction="doSomethingInParent($event)"/>
</template>

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