如何创建具有可导出函数的Vue组件?

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

How to create Vue component with exportable function?

问题

我试图理解如何创建具有可导出函数的组件。
例如:我想创建一个消息框,当我在其他组件中调用从该组件导入的showMessage()方法时,它将显示在屏幕上。
在消息框组件中,我想描述逻辑和模板。
如何实现这一点?非常感谢任何关于此的文档/文章,如果有的话。

英文:

I am trying to understand how to create components with exportable functions.
For example: i want to create message box, that will appear on screen when in some other component i call method showMessage() imported from this component.
In message box component i want to describe logic and template.
How to reach this? Very appreciate any docs/articles about this, if any.

答案1

得分: 0

  1. 在 App.vue(或其他全局文件)中挂载您的消息组件,

  2. 使用存储中的函数来控制其属性

例如

<MyMessage :value="isOpen" :title="title" :message="message" />

...
<script setup>
...
const isOpen = reactive(piniaStore().message.isOpen);
const title = computed(() => piniaStore().message.title);
...
</script>
// 存储
const message = reactive({});

// 做响应式操作...
const showMessage = (title, _message) => {
   message.title = title;
   message.message = _message;
   message.isOpen = true;
}
...

然后,您可以在任何地方使用 piniaStore().showMessage(...) 调用消息

(此代码是一个概念,如果要正确运行,需要进一步开发...)

但我认为您可以使用 Quasar 框架 - Dialog($q.dialog 恰好是您所需要的!)
Ionic 框架 - alertVuetify - dialog api 等(每个框架都有这些功能)

英文:
  1. mount your message component in App.vue (or in other global file),

  2. control its props with function in store

like

&lt;MyMessage :value=&quot;isOpen&quot; :title=&quot;title&quot; :message=&quot;message&quot; /&gt;

...
&lt;script setup&gt;
...
const isOpen = reactive(piniaStore().message.isOpen);
const title = computed (() =&gt; piniaStore().message.title);
...
&lt;/script&gt;
// store
const message = reactive({{});

// do reactive things..
const showMessage(title, _message) =&gt; {
   message.title = title;
   message.message = _message;
   message.isOpen = true;
}
...

then you can call the message with piniaStore().showMessage(...) wherever you want

(this code is a concept, you have to develop if you want to run properly..)


but i think you can use Quasar framework - Dialog ($q.dialog is exactly what you need!)
or Ionic framework - alert, Vuetify - dialog api etc (every framework has these things)

huangapple
  • 本文由 发表于 2023年5月24日 22:08:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76324472.html
匿名

发表评论

匿名网友

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

确定