【问题标题】:Guidance in executing conditional statement within a Vue method在 Vue 方法中执行条件语句的指导
【发布时间】:2019-06-18 19:12:39
【问题描述】:

我在Vue中有以下方法:

shareSubmit: function (schoolId, schoolName, schoolType) {
  this.$eventBus.$emit('share-school-event', {
    schoolId: schoolId,
    schoolName: schoolName,
    schoolType: 'school/' + schoolType,
    schoolAbbr: ''
  });
},

我想做的是根据“schoolType”设置“schoolAbbr”。例如,如果 schoolType 是“college”,我想将 'schoolAbbr' 设置为“c”。

我试过了,但没有运气:

shareSubmit: function (schoolId, schoolName, schoolType) {
  this.$eventBus.$emit('share-school-event', {
    schoolId: schoolId,
    schoolName: schoolName,
    schoolType: 'school/' + schoolType,
    if (schoolType == 'college' {
      schoolAbbr: 'c';
    }
  });
},

【问题讨论】:

    标签: vue.js vuejs2 vue-component


    【解决方案1】:

    问题是您试图访问定义它的同一对象内的 schoolType 属性。更简单的方法是将要成为 schoolType 的变量放在 . ...$emit(。那么你可以在这两个地方使用那个变量。

      var innerSchoolType = 'school/' + schoolType;
      var schoolAbbr = //logic based on innerSchoolType here
    
      this.$eventBus.$emit('share-school-event', {
        schoolId: schoolId,
        schoolName: schoolName,
        schoolType: innerSchoolType,
        schoolAbbr: schoolAbbr
      });
    },```
    

    【讨论】:

      【解决方案2】:

      您可以在 ES6 中使用 Spread syntax,如下所示:

      shareSubmit: function (schoolId, schoolName, schoolType) {
        this.$eventBus.$emit('share-school-event', {
          schoolId: schoolId,
          schoolName: schoolName,
          schoolType: 'school/' + schoolType,
          ...(schoolType == 'college' ? {schoolAbbr: 'c'}: {}),
        });
      },
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-03
        • 1970-01-01
        • 1970-01-01
        • 2020-07-10
        • 1970-01-01
        相关资源
        最近更新 更多