我是vue.js的新手。 如果输入值为空,我想将输出文本更改为占位符中的相同字符串。 这是我想要的代码
<div id="form">
<input class="input-f" type="text" placeholder="please enter your first name" v-model="firstName">
<input class="input-l" type="text" placeholder="please enter your last name" v-model="lastName">
<div class="output">
<p class="f">{{firstName}}</p>
<p class="l">{{lastName}}</p>
</div>
vuejs with jquery
(function(window) {
var data = {
firstName: "Stack",
lastName: "Overflow",
}
var vm = new Vue({
el: "#form",
data: data,
watch: {
firstName: function(v) {
if (!v) {
$(".f").text($(".input-f").attr("placeholder"))
}
},
lastName: function(v) {
if (!v) {
$(".l").text($(".input-l").attr("placeholder"))
}
}
}
})
})(window)
另外,如果我将输入框留空,则数据不会再次绑定。 请告诉我如何实现它? https://jsfiddle.net/je491vas/
答案 0 :(得分:4)
@charith大部分都在那里。您应该将占位符文本添加到数据中,然后将其绑定到输入,并在匹配数据不可用时将其显示在输出中。
let data = {
firstName: "",
lastName: "",
lastNamePlaceHolder: "please enter your last name",
firstNamePlaceHolder: "please enter your first name"
}
new Vue({
el:"#form",
data
})
模板
<div id="form">
<input class="input-f" type="text" :placeholder="firstNamePlaceHolder" v-model="firstName">
<input class="input-l" type="text" :placeholder="lastNamePlaceHolder" v-model="lastName">
<div class="output">
<p class="f">{{firstName || firstNamePlaceHolder }}</p>
<p class="l">{{lastName || lastNamePlaceHolder}}</p>
</div>
</div>
答案 1 :(得分:0)
如果输入文本为空,则希望设置占位符文本。这在默认情况下有效,您无需编写任何其他逻辑。这是占位符的行为。
请参阅以下代码:
<div id="form">
<input class="input-f" type="text" placeholder="please enter your first name" v-model="firstName">
<input class="input-l" type="text" v-bind:placeholder="placeholder" v-model="lastName">
<div class="output">
<p class="f">{{firstName}}</p>
<p class="l">{{lastName}}</p>
</div>
</div>
(function(window) {
var data = {
firstName: "",
lastName: "",
placeholder:"please enter your last name"
}
var vm = new Vue({
el: "#form",
data: data
})
})(window)
您可以使用上述任一方式定义占位符:
v-bind:placeholder="placeholder"
placeholder="please enter your first name"