可以将组件的功能转移到vue中的其他文件中吗?

问题描述 投票:0回答:2

我的 vue 组件中有多个这样的函数。有什么方法可以将函数转移到其他文件中,然后将它们导入到此处。这是我的

App.vue

  getLocation: async function () {
   
    },
    subscribe: function (longitude, latitude) {


    },

    async openLocationWarning() {

     
    },
    uploadData(data, key) {
    
    },
    downloadData()
    {
      
    }
javascript vue.js vuejs3
2个回答
0
投票

不,你不能,但你可以使用mixins。您也可以将其存储在js文件中并导出。

export yourFunction() {

}

export anotherFunction(){
}

并将其导入到您的文件中

import {yourFunction, anotherFunction} from 'path/to/your_file';

methods: {
  callSomeFunction() {
    // you can call it like this.
    yourFunction();
  }
}

0
投票

答案是“是”——可以。 您可以通过将“this”上下文绑定到您的函数中来实现此目的(请参阅https://www.linkedin.com/pulse/what-difference- Between-call-apply-bind-muhammad-rizwan

摘录

在JavaScript中,call、apply和bind方法用于调用函数并在该函数内设置“this”值。 call 方法用于调用函数并为函数指定“this”值。它需要两个参数:用作函数内“this”值的值,以及要传递给函数的可选参数列表。 apply方法与call方法类似,但不是指定 单独传递给函数的参数,它需要一个数组 要传递给函数的参数。

示例(来自我链接的网站)

function greet(greeting) {
  console.log(greeting + " " + this.name);
}

var personl = {
  name: "Alice",
};
var person2 = {
  name: "Bob",
};
greet.call(personl, "Hello"); // outputs "Hello Alice
greet.apply(person2, ["Hi"]); // outputs "Hi Bob

var greetPersonl = greet.bind(personl);
greetPersonl("Hello"); // outputs "Hello Alice
© www.soinside.com 2019 - 2024. All rights reserved.