Vue獲取input值的四種常用方法
更新時間:2023年09月17日 10:00:45 作者:凡大來啦
Vue是一種流行的Web開發(fā)框架,它提供了一個雙向綁定的語法糖。在Vue中,我們可以很容易地獲取頁面上的數據,并且可以實時的響應其變化,這篇文章主要給大家介紹了關于Vue獲取input值的四種常用方法,需要的朋友可以參考下
1. v-model 表單輸入綁定
//使用v-model創(chuàng)建雙向數據綁定, 用來監(jiān)聽用戶的輸入事件以更新數據,并對一些極端場景進行一些特殊處理
<template>
<div>
<input class="login-input" type="text" v-model="username" placeholder="請輸入賬號">
<input class="login-input" type="password" v-model="password" placeholder="請輸入密碼">
<div class="login-button" @click="login" type="submit">登陸</div>
</div>
</template>
<script>
export default {
name: 'Login',
data() {
return {
username: '',
password: ''
}
},
methods: {
login() {
console.log(this.username)
console.log(this.password)
}
}
}
<script/>
2. @input 監(jiān)聽輸入框
//輸入框只要輸入的值變化了就會觸發(fā) input 調用 search
<template>
<div class="class">
<div>
<input type="text" @input="search"/>
</div>
</div>
</template>
<script>
export default {
name: "Search",
data() {
},
methods: {
search(event){
console.log( event.currentTarget.value )
}
}
}
</script>3. @change 監(jiān)聽輸入框
//輸入框失去焦點時,輸入的值發(fā)生了變化,就會觸發(fā) change 事件
<template>
<div class="class">
<div>
<input type="text" @change="search"/>
</div>
</div>
</template>
<script>
export default {
name: "Search",
data() {
},
methods: {
search(event){
console.log( event.target.value )
}
}
}
</script>4. ref 獲取數據
//這種方式類似于原生DOM,但是ref獲取數據更方便
<template>
<div class="class">
<input type="text" ref="inputDom" />
<button @click="subbmitButton">獲取表單數據</button>
</div>
</template>
<script>
export default {
name: "Page",
data() {
},
methods: {
subbmitButton(){
console.log( this.$refs.inputDom.value )
}
}
}
</script>附:vue如何判斷輸入框是否有值
在Vue中判斷輸入框是否有值的方法有多種。以下是其中兩種常用的方法:
- 綁定v-model指令:將輸入框的值綁定到Vue實例的數據屬性上,然后通過判斷該數據屬性的值來判斷輸入框是否有值。例如:
<template>
<input type="text" v-model="inputValue" />
<button @click="checkInput">檢查輸入框是否有值</button>
</template>
<script>
export default {
data() {
return {
inputValue: ''
}
},
methods: {
checkInput() {
if (this.inputValue) {
console.log('輸入框有值')
} else {
console.log('輸入框為空')
}
}
}
}
</script>- 使用ref引用:給輸入框添加一個ref屬性,然后通過$refs來獲取輸入框元素的引用,再通過判斷輸入框元素的value屬性來判斷輸入框是否有值。例如:
<template>
<input type="text" ref="myInput" />
<button @click="checkInput">檢查輸入框是否有值</button>
</template>
<script>
export default {
methods: {
checkInput() {
if (this.$refs.myInput.value) {
console.log('輸入框有值')
} else {
console.log('輸入框為空')
}
}
}
}
</script>總結
到此這篇關于Vue獲取input值的四種常用方法的文章就介紹到這了,更多相關Vue獲取input值內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue3+vite中使用import.meta.glob的操作代碼
在vue2的時候,我們一般引入多個js或者其他文件,一般使用? require.context 來引入多個不同的文件,但是vite中是不支持 require的,他推出了一個功能用import.meta.glob來引入多個,單個的文件,下面通過本文介紹vue3+vite中使用import.meta.glob,需要的朋友可以參考下2022-11-11
Vue3+Element-plus項目自動導入報錯的解決方案
vue3出來一段時間了,element也更新了版本去兼容vue3,下面這篇文章主要給大家介紹了關于Vue3+Element-plus項目自動導入報錯的解決方案,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-07-07
vue監(jiān)聽瀏覽器的后退和刷新事件,阻止默認的事件方式
這篇文章主要介紹了vue監(jiān)聽瀏覽器的后退和刷新事件,阻止默認的事件方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10

