在 Vue 模板中调用服务方法

Dal*_*bor 2 javascript vue.js vuejs3

我有

<template>
  <button @click="doSomething">...</button>
</template>

<script>
import ApiService from '../service/api.service';
export default {
  setup() {
      function doSomething() {
        ApiService.doSomething();
      }
      return {
        doSomething
      }
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

如果我让它更短(就像我在 Angular 中使用的那样):

<template>
  <button @click="ApiService.doSomething">...</button>
</template>

<script>
import ApiService from '../service/api.service';
</script>
Run Code Online (Sandbox Code Playgroud)

它不起作用,引发运行时错误。(即使我尝试作为函数调用它也不起作用:@click="ApiService.doSomething()"

你能帮忙吗,如何节省时间/代码并直接在模板中调用ApiService.doSomething


PS 他们让我也发布 ApiService 所以这里是:api.service.js:

import axios from 'axios';
import router from '@/router';

const ApiService = {

    init(baseURL) {
        axios.defaults.baseURL = baseURL;
    },

    //...

    doSomething() {
        router.push({ path: '/goSomewhere' });
    },

}

export default ApiService
Run Code Online (Sandbox Code Playgroud)

Dan*_*iel 5

它不起作用,因为您需要将其传递setup给模板中可用的函数。

你可以这样做:

<template>
  <button @click="ApiService.doSomething">...</button>
</template>

<script>
import ApiService from '../service/api.service';
export default {
  setup() {
      return { ApiService }
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

或者,您也可以使用setup脚本的属性,它为您做一些提升魔法。( RFC 链接)

<template>
  <button @click="ApiService.doSomething">...</button>
</template>

<script setup>
import ApiService from '../service/api.service';
export ApiService;
</script>
Run Code Online (Sandbox Code Playgroud)