如何在子组件中使用父 Vue 组件的函数?

huangapple go评论52阅读模式
英文:

How to use function from parent Vue component in child?

问题

Parent 组件中,您希望每隔 1 秒自动调用 checkStatus 函数。您可以使用 JavaScript 的 setInterval 函数来实现这个目标。以下是修改后的代码:

<template>
  <Dialog :msg="message" />
</template>
<script>
export default defineComponent({
  setup() {
    const message = ref({
      text: '',
    });

    const checkStatus = (*some variables*) => {
      message.value.text = 'Loading...';
      // 在此添加您的数据处理逻辑

      return message;
    }

    // 每隔 1 秒自动调用 checkStatus 函数
    setInterval(checkStatus, 1000);

    return {
      message,
    }
  }
})
</script>

现在,checkStatus 函数将每隔 1 秒自动执行一次,并将结果传递给子组件。

Child 组件的代码保持不变。

英文:

I've got a problem. In parent component I get some data, calculate them and then return to props for child component. Now I call this function on button click, but I want to call it automatically for example every 1 sec. How can I do it?

Parent:

&lt;template&gt;
&lt;Dialog :msg=&quot;message&quot;/&gt;
&lt;/template&gt;
&lt;script&gt;
export default defineComponent({
  const message = ref({
      text: &#39;&#39;,
  });
  return{

    checkStatus: (*some variables*) =&gt; {
        message.value.text = &#39;Loading...&#39;
        return message;
    }
  }
})
&lt;/script&gt;

Child:

&lt;template&gt;
  &lt;h3&gt;{{msg.text}}&lt;/h3&gt;
&lt;/template&gt;
&lt;script&gt;
export default defineComponent({
  props:[&#39;msg&#39;]
})
&lt;/script&gt;

</details>


# 答案1
**得分**: 1

你可以设置一个定时器来调用函数,例如,每隔5秒调用`checkStatus`,添加以下代码:

```javascript
setInterval(() => {
   this.checkStatus()
}, 5000)
英文:

You can set a timer to call the function as follows - for example to call checkStatus every 5 seconds, add:

setInterval(()=&gt;{
   this.checkStatus()
},5000)

huangapple
  • 本文由 发表于 2023年3月4日 05:25:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75632008.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定