programing

조건에 따른 VueJS HTML 요소 유형

prostudy 2022. 5. 3. 20:55
반응형

조건에 따른 VueJS HTML 요소 유형

Vue JS에서는 할 수 있다.

<h1 v-if="someCondition">MY TITLE</h1>

어떤 조건에서 원소 타입을 베이스로 할 수 있는 방법이 있는가?

예를 들어, 다음을 기반으로 한다.someCondition나는 내 직함을 원한다.<h1>또는<h2>.

내가 할 수 있을 것 같다.

<template v-if="someCondition === 0">
  <h1>MY TITLE</h1>
</template>

<template v-if="someCondition === 1">
  <h2>MY TITLE</h2>
</template>

하지만 이것을 쓰는 더 솔직한 방법이 있을까?

<component :is="'h'+someCondition">MY TITLE</component>

"SomeCondition"은 소품 또는 데이터 속성으로 정의될 수 있으며, "H 태그"만 사용할 경우 1에서 6까지의 값을 가질 수 있다.

두 가지 변주곡만 있다면 계속 따라가는 것이 가장 좋다.v-if그리고v-else.

가능한 변형이 더 있을 경우 동적 구성요소를 사용하는 방법(https://vuejs.org/v2/guide/components-dynamic-async.html)

<component :is="dynamicComponent">Foo</component>

...

computed: {
  dynamicComponent() {
    return 'h'+this.i
  }
}

그 다음엔 로 렌더링될 것이다.<h1>,<h2>,<h{i}>HTML이 아닌 실제 구성요소 간에 전환할 때 더 유용함h꼬리표를 달다

https://codesandbox.io/s/vue-template-z40u7

여기가 바로 그곳이다.render기능은 유용하다.템플리트가 더 고급 로직을 필요로 할 때마다 렌더링 함수는 HTML 태그가 아닌 템플릿을 생성하기 위해 Javascript의 모든 로직 흐름 용량과 함께 Javascript를 사용할 수 있다.여기서 Vue의 렌더링 기능에 대해 자세히 알아보십시오.

다음은 이 예를 보여 주는 바이올린이다.

data() {
  return {
    someCondition: 1
  }
},
render(h){
  let tagType;
  if (this.someCondition === 0) {
    tagType = 'h1';
  } else if(this.someCondition === 1) {
    tagType = 'h2';
  }
  return h(tagType, null, 'MY TITLE');
}

참조URL: https://stackoverflow.com/questions/56187750/vuejs-html-element-type-based-on-condition

반응형