[javascript] VueJS는 조건부로 요소에 대한 속성을 추가합니다.

VueJS에서는 v-if를 사용하여 DOM 요소를 추가하거나 제거 할 수 있습니다.

<button v-if="isRequired">Important Button</button>

그러나 dom 요소의 속성을 추가 / 제거하는 방법이 있습니다. 예를 들어 다음의 경우 필수 속성을 조건부로 설정합니다.

Username: <input type="text" name="username" required>

비슷한 방법으로 :

Username: <input type="text" name="username" v-if="name.required" required>

어떤 아이디어?



답변

시험:

<input :required="test ? true : false">


답변

가장 간단한 형태 :

<input :required="test">   // if true
<input :required="!test">  // if false
<input :required="!!test"> // test ? true : false


답변

<input :required="condition">

테스트진실<input :required="test ? true : false"> 이면 이미 속성을 얻고 테스트거짓 이면 속성을 얻지 못 하기 때문에 필요하지 않습니다 . 부분은 많은 같이, 중복 …requiredtrue : false

if (condition) {
    return true;
} else {
    return false;
}
// or this...
return condition ? true : false;
// can *always* be replaced by...
return (condition); // parentheses generally not needed

이 바인딩을 수행하는 가장 간단한 방법은 <input :required="condition">

테스트 (또는 조건 )가 잘못 해석 될 수있는 경우에만 다른 작업을 수행해야합니다. 이 경우 Syed의 사용이 !!트릭 을 수행합니다.
  <input :required="!!condition">


답변

boolean강제로 전달할 수 있으며 !!변수 앞에 놓을 수 있습니다 .

let isRequired = '' || null || undefined
<input :required="!!isRequired"> // it will coerce value to respective boolean 

하지만 수신 컴포넌트가 type소품에 대해 정의한 다음 경우에 대해주의를 기울이고 싶습니다 . 이 경우 isRequired유형을 정의한 경우 string전달 boolean하면 유형 검사가 실패하고 Vue 경고가 표시됩니다. 해당 소품을 전달하지 않으려는 문제를 해결하려면 undefinedfallback을 넣으면 소품이component

let isValue = false
<any-component
  :my-prop="isValue ? 'Hey I am when the value exist' : undefined"
/>

설명

나는 같은 문제를 겪었고 위의 해결책을 시도했습니다 !! 예, 나는 보이지 prop않지만 실제로 여기에서 필요한 것을 충족하지 못합니다.

내 문제 –

let isValid = false
<any-component
  :my-prop="isValue ? 'Hey I am when the value exist': false"
/>

위의 경우, 내가 한되지 기대했던 my-prop아이 컴퍼넌트에 전달받을 – <any-conponent/>I가 표시되지 않습니다 propDOM있지만 내에서 <any-component/>구성 요소 오류가 소품 유형 검사 실패의 튀어 나옵니다. 하위 구성 요소로서, 나는 기대하고 my-prop을 수 String있지만입니다 boolean.

myProp : {
 type: String,
 required: false,
 default: ''
}

즉, 자식 구성 요소가 false. 여기서 조정은 자식 구성 요소가 default-value검사를 건너 뛰도록하는 것입니다. undefined그래도 합격 !

<any-component
  :my-prop="isValue ? 'Hey I am when the value exist' : undefined"
/>
 

이것은 작동하고 내 자식 소품에는 기본값이 있습니다.


답변

HTML 사용

<input :required="condition" />

그리고 같은 데이터 속성에서 정의

data () {
   return {
      condition: false
   }
}


답변