gpt4 book ai didi

javascript - Vue.js 通过函数访问元素

转载 作者:行者123 更新时间:2023-12-03 06:47:52 26 4
gpt4 key购买 nike

当我关注标签下方的输入元素时,我需要向标签元素添加类。我目前的解决方案是这样的:

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 为重点的类。如何选择最近的标签元素并编辑它的类?

最佳答案

更好的方法是使用动态类。看这个例子:

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>

关于javascript - Vue.js 通过函数访问元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62003300/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com