DEV Community

Cover image for Vue理解v-model內部運作
周柏諭 BO-YU CHOU
周柏諭 BO-YU CHOU

Posted on • Edited on

Vue理解v-model內部運作

前言

在Vue中,inputselecttextarea等tag會利用v-model這個屬性來做雙向綁定

<input v-model="email" />
Enter fullscreen mode Exit fullscreen mode

上面的code相當於下面的code

<input :value="email" @input="e => email = e.target.value" />
Enter fullscreen mode Exit fullscreen mode

在 component 使用 v-model

<basic-input v-model="email" />
Enter fullscreen mode Exit fullscreen mode

元件code

<template>
  <input @input="handleInput" />
</template>

<script>
export default {
  prop: ['value'],
  data () {
    return {
      content: this.value
    }
  },
  methods: {
    handleInput (e) {
      this.$emit('input', this.content)
    }
  }
}
</script>
Enter fullscreen mode Exit fullscreen mode

重點是子元件內要註冊名為value的props

參考文章

https://ithelp.ithome.com.tw/articles/10250089

https://www.digitalocean.com/community/tutorials/how-to-add-v-model-support-to-custom-vue-js-components

Top comments (0)