溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在vue.js中實(shí)現(xiàn)v-model雙向數(shù)據(jù)綁定

發(fā)布時間:2021-05-07 15:50:56 來源:億速云 閱讀:178 作者:Leah 欄目:web開發(fā)

本篇文章為大家展示了怎么在vue.js中實(shí)現(xiàn)v-model雙向數(shù)據(jù)綁定,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

我們都清楚v-model其實(shí)就是vue的一個語法糖,用于在表單控件或者組件上創(chuàng)建雙向綁定。

//表單控件上使用v-model
<template>
 <input type="text" v-model="name" />
 <input type="checkbox" v-model="checked"/>
 <!--上面的input和下面的input實(shí)現(xiàn)的效果是一樣的-->
 <input type="text" :value="name" @input="name=e.target.vlaue"/>
 <input type="checkBox" :checked="checked" @click=e.target.checked/>
 {{name}}
</template>
<script>
export default{
 data(){
  return {
   name:"",
   checked:false,
  }
 }
}
</script>

vue中父子組件的props通信都是單向的。父組件通過props向下傳值給子組件,子組件通過$emit觸發(fā)父組件中的方法。所以自定義組件是無法直接使用v-model來實(shí)現(xiàn)v-model雙向綁定的。那么有什么辦法可以實(shí)現(xiàn)呢?

//父組件
<template>
 <div>
  <c-input v-model="form.name"></c-input>
  <c-input v-model="form.password"></c-input>
  <!--上面的input等價于下面的input-->
 <!--<c-input :value="form.name" @input="form.name=e.target.value"/>
  <c-input :value="form.password" @input="form.password=e.target.value"/>-->
 </div>
</template>
<script>
import cInput from "./components/Input"
export default {
 components:{
  cInput
 },
 data() {
  return {
   form:{
    name:"",
    password:""
   },
   
  }
 },
}
</script>
//子組件 cInput
<template>
  <input type="text" :value="inputValue" @input="handleInput">
</template>
<script>
export default {
 props:{
  value:{
   type:String,
   default:"",
   required:true,
  }
 },
 data() {
  return {
   inputValue:this.value,
  }
 },
 methods:{
  handleInput(e){
   const value=e.target.value;
   this.inputValue=value;
   this.$emit("input",value);
  },
 }
}
</script>

根據(jù)上面的示例代碼可以看出,子組件c-input上綁定了父組件form的值,在子組件中通過:value接收了這個值,然后我們在子組件中修改了這個值,并且通過$emit觸發(fā)了父組件中的input事件將修改的值又賦值給了form。

上述內(nèi)容就是怎么在vue.js中實(shí)現(xiàn)v-model雙向數(shù)據(jù)綁定,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI