在Vue方法中执行条件语句的指南

时间:2019-01-24 23:41:03

标签: vue.js vuejs2 vue-component

我在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';
    }
  });
},

2 个答案:

答案 0 :(得分:0)

问题是您要尝试在定义该对象的同一对象内访问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
  });
},```

答案 1 :(得分:0)

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

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