在 Vue 中基於 props 顯示有條件渲染的文字的替代方法?
P粉021854777
P粉021854777 2024-03-27 22:23:56
0
2
470

我有一個根據使用者成員資格狀態呈現文字的元件,我想根據該屬性值更改插值文字。除了使用 v-ifv-show 的一堆 div/p 標籤之外,是否有更有效的方法根據 prop 顯示不同的文字?

不斷地有一堆堆疊的 div 只是大量的文字。

如有任何建議,我們將不勝感激!

乾杯!

<script lang="ts" setup>
import { PropType } from 'vue'

const props = defineProps({
  kind: {
    type: String as PropType<'subscribed' | 'unsubscribed'>,
    default: 'subscribed',
  },
  planId: {
    type: String as PropType<'standard' | 'silver' | 'gold' | 'platinum' | 'diamond' | 'no plan'>,
    default: 'standard',
  },
})
</script>

<template>
  <div class="c-promotion-plan-card" data-cy="component-promotion-plan-card">
    <div class="flex items-baseline mb-sm">
      <div v-if="planId === 'standard'" class="text-h6 text-dark">Standard Gang</div>
      <div v-if="planId === 'silver'" class="text-h6 text-dark">Silver Foxes</div>
      <div v-if="planId === 'gold'" class="text-h6 text-dark">Golden Girls</div>
      <div v-if="planId === 'platinum'" class="text-h6 text-dark">Platinum Boys</div>
      <div v-if="planId === 'diamond'" class="text-h6 text-dark">Diamond Dudes</div>
      <div v-if="planId === 'no plan'" class="text-h6 text-dark">
        No Plan Posse
      </div>
    </div>
  </div>
</template>

P粉021854777
P粉021854777

全部回覆(2)
P粉447002127

是的,有更好的方法。 您可以定義一個計算屬性,例如 Vue2 語法

computed: {
 getLabel() {
  // Assuming that 'planId' is the dependency prop
  if(this.planId === 'standard') return 'Standard Gang';
  else if(this.planId === 'silver') return 'Silver Foxes';
  ....
  return 'No Plan Posse' // For 'no plan' condition
 }

Vue3 語法

#
setup(props) {
 // 1.getLabel depends on firstName,lastName.
 const getLabel = computed(() => {
  // Assuming that 'planId' is the dependency prop
  if(props.planId === 'standard') return 'Standard Gang';
  else if(props.planId === 'silver') return 'Silver Foxes';
  ....
  return 'No Plan Posse' // For 'no plan' condition
 });
 return {
  getLabel,
 };
},

然後在模板內呼叫插值計算,例如

{{getLabel}}
P粉245276769

也許類似於以下程式碼片段(映射您的計劃並使用計算屬性):

const { ref, computed } = Vue
const app = Vue.createApp({
  props: {
    kind: {
      type: String,
      default: 'subscribed',
    },
    planId: {
      type: String,
      default: 'standard',
    },
  },
  setup(props) {
    const plans = ref([{plan:'standard', name: 'Standard Gang'}, {plan:'silver', name: 'Silver Foxes'}, {plan:'gold', name: 'Golden Girls'}, {plan:'platinum', name: 'Platinum Boys'}, {plan:'diamond', name: 'Diamond Dudes'}, {plan: 'no plan', name: 'No Plan Posse'}])
    const handlePlan = computed(() => plans.value.find(p => p.plan === props.planId))
    return { plans, handlePlan }
  },
})
app.mount('#demo')
.style-class {
  color: red;
  font-size: 2em;
}
.other-style {
  color: blue;
}
sssccc
{{ handlePlan.name }}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板