如何让 Switch/Case 只查看特定断点?

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

我正在运行一个查看 Vuetify 断点的 switch/case,但它不只是获取名称并提供我想要的 int,它最终总是获取“limitSize”变量的最高数字。

这是我正在开发的新闻滑块,根据断点,它在滑块中显示一个、两个或三个元素。我尝试为变量指定默认值,但这不起作用。我最好希望 SM & down 为 1,MD 为 2,LG & Up 为 3,但我不确定实现这一目标的正确方法是什么。任何帮助将不胜感激。

以下是位于计算属性内的 Switch/Case。我还附上了代码当前结果的图像(当我想要 2 时,图像位于 MD 窗口上)

VueJS

   pageOfWhatsNews() {
      var limitSize;
      switch (this.$vuetify.breakpoint.name) {
        case "xs":
          limitSize = 1;
        case "sm":
          limitSize = 1;
        case "md":
          limitSize = 2;
        case "lg":
          limitSize = 3;
        case "xl":
          limitSize = 3;
      }
      var start = (this.currentPage - 1) * limitSize;
      var end = (this.currentPage - 1) * limitSize + limitSize;
      return this.whatsNews.slice(start, end);
    }

vue.js switch-statement vuetify.js
1个回答
5
投票

嗯,这是因为您在

break
之间缺少
switch cases
语句。查看下面
switch-case
块的正确语法:

开关大小写语法

const expr = 'Papayas';
switch (expr) {
  case 'Oranges':
    console.log('Oranges are $0.59 a pound.');
    break;
  case 'Mangoes':
  case 'Papayas':
    console.log('Mangoes and papayas are $2.79 a pound.');
    // expected output: "Mangoes and papayas are $2.79 a pound."
    break;
  default:
    console.log(`Sorry, we are out of ${expr}.`);
}

解决方案

function pageOfWhatsNews() {
  var limitSize;
  switch (this.$vuetify.breakpoint.name) {
    case "xs":
      limitSize = 1;
      break;
    case "sm":
      limitSize = 1;
      break;
    case "md":
      limitSize = 2;
      break;
    case "lg":
      limitSize = 3;
      break;
    case "xl":
      limitSize = 3;
      break;
  }
  var start = (this.currentPage - 1) * limitSize;
  var end = (this.currentPage - 1) * limitSize + limitSize;
  
  console.log(limitSize);
  // return this.whatsNews.slice(start, end);
}

// Just for demo
this.$vuetify = {breakpoint: {name: 'md'}};
pageOfWhatsNews();

优化解决方案

我还建议您放置

md
lg
xl
断点案例,并将其余断点案例回退到
default
案例。

function pageOfWhatsNews() {
  var limitSize;
  switch (this.$vuetify.breakpoint.name) {
    case "md":
      limitSize = 2;
      break;
    case "lg":
    case "xl":
      limitSize = 3;
      break;
    default: 
      limitSize = 1;
  }
  var start = (this.currentPage - 1) * limitSize;
  var end = (this.currentPage - 1) * limitSize + limitSize;
  
  console.log(limitSize);
  // return this.whatsNews.slice(start, end);
}

// Just for demo
this.$vuetify = {breakpoint: {name: 'sm'}};
pageOfWhatsNews();

© www.soinside.com 2019 - 2024. All rights reserved.