【问题标题】:Vue 2: Set empty class as data propertyVue 2:将空类设置为数据属性
【发布时间】:2021-12-14 16:42:45
【问题描述】:

我在 Vue 2 中有一个场景,我将 API 类初始化为组件上的数据属性,如下所示:

new Vue({
  el: '#my-element'
  data: {
    apiUrl: apiUrl,
    api: new ApiClient(this.apiUrl)
  }
})

API 客户端:

class ApiClient {
  constructor(apiUrl) {
    this.apiUrl = apiUrl;
  }

  async getRequest() {
    // Perform GET
  }
}

这很好用,但我有需要使用两个不同 API 客户端的场景。如果某个prop 被传递到我的组件中,我想将该数据属性初始化为secondApi,例如。

在这种情况下,我看到自己使用了created() 钩子:

created() {
  if (prop === true) {
    this.secondApi = new SecondApiClient(this.apiUrl);
  }
}

虽然在我的data : { } 对象中,我不确定如何正确初始化这个可选的secondApi 属性(在没有传入prop 的情况下)。我一开始是否将其设置为空对象?它始终是class 对象,例如apiClient。有空类数据类型吗?

【问题讨论】:

  • 是不是像created() { if (prop === true) { this.secondApi = new SecondApiClient(this.apiUrl); } else this.firstApi = new firstApiClient(this.apiUrl); } ????
  • 好问题。不,我将始终初始化第一个 API 类。第二个 API 类是我唯一想要(尝试)有条件地初始化的类。
  • 我会简单地将其初始化为 false,并使 prop 不需要

标签: javascript vue.js vuejs2


【解决方案1】:

是的,您可以按照以下方式之一进行操作

方法一:

data() {
 return {
  apiUrl: apiUrl,
  api: null // or you can even keep it as new ApiClient(this.apiUrl) if that's the default value
 }
},
props: ['certainProperty'],
created() {
  if (this.certainProperty === true) { // certainProperty is a prop
    this.api = new SecondApiClient(this.apiUrl);
  } else this.api = new ApiClient(this.apiUrl);
}

有时收到道具可能会有延迟,所以最好遵循以下方法

方法2:

data() {
 return {
  apiUrl: apiUrl,
  api: null // or you can even keep it as new ApiClient(this.apiUrl) if that's the default value
 }
},
props: ['certainProperty'],
watch: {
 certainProperty(newVal) {
  if (newVal === true) { // certainProperty is a prop
    this.api = new SecondApiClient(this.apiUrl);
  } else this.api = new ApiClient(this.apiUrl);
 }
}

注意:你需要从父组件传递props,比如

<child-component :certainProperty="true" />

【讨论】:

    猜你喜欢
    • 2021-04-24
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    相关资源
    最近更新 更多