在没有事件的情况下调用子组件内的函数?
Calling function inside child component without an event?
目前正在尝试使用属于父级的方法
<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'
如何在不依赖事件的子组件中调用函数?很抱歉问了这么简单的问题,但我在 google 上找到的所有内容都在使用 $emit 和事件。
使用 $emit 调用父级可以监听的函数。
在您使用它的地方,我会建议该函数的计算道具。
但是回到你的问题这里是发射和收听的例子。
//Parent
<template>
<MyComponent @childFunction="doSomethingInParent($event)"/>
</template>
//Child
<template>
<button @click="emitStuff">
</template>
.....
methods:{
emitStuff(){
this.$emit(childFunction, somedata)
}
通过事件,您可以将数据信息提供给父组件。
$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>
目前正在尝试使用属于父级的方法
<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'
如何在不依赖事件的子组件中调用函数?很抱歉问了这么简单的问题,但我在 google 上找到的所有内容都在使用 $emit 和事件。
使用 $emit 调用父级可以监听的函数。
在您使用它的地方,我会建议该函数的计算道具。
但是回到你的问题这里是发射和收听的例子。
//Parent
<template>
<MyComponent @childFunction="doSomethingInParent($event)"/>
</template>
//Child
<template>
<button @click="emitStuff">
</template>
.....
methods:{
emitStuff(){
this.$emit(childFunction, somedata)
}
通过事件,您可以将数据信息提供给父组件。
$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>