【问题标题】:How to call Vue 3 method from outside the app如何从应用程序外部调用 Vue 3 方法
【发布时间】:2022-07-12 22:44:23
【问题描述】:

我想要的是调用一个方法,在页面组件之外的 vue 3 应用程序表单中声明。所以到目前为止我做了什么:

App.vue

<script setup>
 
function test(){
console.log('test');
}
</script>

vue.js

import { createApp } from 'vue'
import App from 'App.vue'

window.app = createApp(App).mount('#app')

index.html

<div id="app"></app>
<script src="app.js"></script>

<script>
 fuction callTest(){
   window.app.test() // <-- this returns undefined
 }
</script>

但是它适用于 vue2。知道如何让它与 vue3 一起工作吗?

【问题讨论】:

    标签: javascript vue.js vuejs3


    【解决方案1】:

    您需要在第一个文件中使用 defineExpose 才能在组件外使用它:

    <script setup>
     
    function test(){
     console.log('test');
    }
    defineExpose({
     test
    })
    </script>
    

    【讨论】:

    猜你喜欢
    • 2021-02-21
    • 2018-05-30
    • 2016-11-07
    • 2020-05-15
    • 1970-01-01
    • 2011-11-10
    • 2015-07-18
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多