簡體   English   中英

如何將依賴項傳遞給Vue組件?

[英]How do I pass a dependency to a Vue component?

我有一個旨在用作使用axios進行AJAX請求的存儲庫的類:

export default class SomeRepository {
  getEncryptedValue (value) {
    return axios.get('http://localhost/api/v1/encrypt')
  }
}

我有一個組件可以在組件的methods屬性內調用此存儲庫的方法,如下所示:

<template>
  ...
</template>

<script>
import SomeRepository from '@/classes/SomeRepository'

export default {
  data () {
    return {
      value: '',
      result: ''
    }
  },
  methods: {
    encrypt () {
      let someRepo = new SomeRepository()

      someRepo.getEncryptedValue(this.value)
        .then(response => {
          this.result = response.data.result
        })
    }
  }
}
</script>

如何傳遞SomeRepository作為依賴項? 我的目標是要在單元測試中模擬它。

我正在尋找一種簡單的解決方案,最好是不涉及第三方庫或樣板的解決方案。

我也嘗試過:

import Vue from 'vue'
import SomeRepository from '@/classes/SomeRepository'

Vue.use(SomeRepository)
// and
Vue.use(new SomeRepository())

這顯然是行不通的(老實說,我沒想到他們會這樣)。 我也嘗試按照這篇文章https://codeburst.io/dependency-injection-with-vue-js-f6b44a0dae6d進行操作,但我真的不喜歡每次要使用依賴項時都必須創建mixin的方法。

我也考慮過將它作為道具傳遞,但是不確定在傳遞它之前在哪里實例化該對象。

有很多模擬函數的方法。 我發現最簡單的方法就是簡單地接受依賴項作為函數的參數,然后替換要在測試中使用的函數。

方法示例

// Function
function func(dependency) {
  dependency.use()
}

// In App
func(dependency) // -> runs dependency.use

// In Tests
func(mockDependency) // -> runs mocked dependency.use

你的例子

一旦知道了這種方法,您就可以做很多不同的版本,但是要顯示一個超級簡單的版本。

encrypt() {
  this._encrypt(SomeRepository)
}
_encrypt (SomeRepository) {
  let someRepo = new SomeRepository()

  someRepo.getEncryptedValue(this.value)
    .then(response => {
      this.result = response.data.result
    })
}

您將使用模擬依賴項測試_encrypt。

您也可以這樣做。

encrypt (_SomeRepository=SomeRepository) {
  let someRepo = new _SomeRepository()

  someRepo.getEncryptedValue(this.value)
    .then(response => {
      this.result = response.data.result
    })
}

如果您傳遞了模擬版本,那么如果不使用它,它將使用真實版本。 想法是使用這種方法,但是您認為合適,但我認為您可以理解。 它非常簡單,不需要任何魔術,也不需要庫。

您應該使用Vue插件https://vuejs.org/v2/guide/plugins.html然后可以通過this.$someDeps訪問它

對於單元測試,您可以使用Vue Test Utils https://vue-test-utils.vuejs.org/api/options.html#mocks輕松對其進行模擬

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM