簡體   English   中英

Vue.js 通過 function 訪問元素

[英]Vue.js accessing element via function

當我關注低於 label 的輸入元素時,我需要將 class 添加到 label 元素。 我目前的解決方案是這樣的:

HTML:

<label for="formProductId" ref="productIdLabel" class="form-element-title">Product ID</label>
<input id="formProductId" @blur="toggleFocus('productIdLabel', false)" @focus="toggleFocus('productIdLabel', true)" v-model="filterValues.productId" :name="filterOptions.productId === true ? 'productId' : false" type="text">

JS:

toggleFocus(ref: string, enable: boolean) {
    if (enable) {
        (this.$refs[ref] as HTMLElement).classList.add("js-focused");
    } else {
        (this.$refs[ref] as HTMLElement).classList.remove("js-focused");
    }
}

我想刪除 ref 屬性並完全由所選元素本身切換以 js 為中心的 class 。 我如何 select 最接近的 label 元素並編輯它的 class?

您可以將previousElementSiblingevent.target一起使用。

例子:

 new Vue({ el: '#app', methods: { toggleLabelColor(event) { event.target.previousElementSibling.classList.toggle('input-focused') } } })
 input { display: block; }.input-focused { color: green; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <label>I turn green when focused.</label> <input @focus="toggleLabelColor" @blur="toggleLabelColor"> <label>I turn green when focused.</label> <input @focus="toggleLabelColor" @blur="toggleLabelColor"> <label>I turn green when focused.</label> <input @focus="toggleLabelColor" @blur="toggleLabelColor"> </div>

更好的方法是使用動態 class。 看這個例子:

 new Vue({ el: '#app', data: { productIdLabel: false } })
 .js-focused { background-color: lightblue; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id='app'> <label for="formProductId" class="form-element-title":class="{'js-focused': productIdLabel == true}">Product ID</label> <input id="formProductId" @blur="productIdLabel = false" @focus="productIdLabel = true" type="text"> </div>

與組件和多個表單輸入一起使用:

 Vue.component("form-label", { template: `<div> <label:for="info.id" class="form-element-title":class="{'js-focused': isFocused == true}">{{info.label}}</label> <input:id="info.id" @blur="isFocused = false" @focus="isFocused = true" type="text"> </div>`, props: ["info"], data: function(){ return { isFocused: false } } }) new Vue({ el: '#app', data: { form: [{ label: "Product Id", id: "formProductId" }, { label: "Another Element", id: "anoterId" }, { label: "Third Element", id: "thirdId" }] } })
 .js-focused { background-color: lightblue; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id='app'> <form-label v-for='el in form':info='el'></form-label> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM