iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 26
0
Modern Web

技術在走,Vue.js 要有系列 第 26

|D26| 自定義元件的資料綁定與`$event`

  1. 我們定義了一個 my-input 元件,以符合設計稿需求
<template>
  <input class="my-input" type="text" placeholder="電話,例:0912-345-678">
</template>
<style lang="scss">
.my-input {
  font-size: 20px;
  padding: 5px 10px;
  border: 1px solid gray;
  border-radius: 5px;
  color: burlywood;
}
</style>
  1. 接著在父元件使用 my-input 元件,父元件的 components 紀錄我們 import 進來的子元件
<template>
  <h1>父元件</h1>
  <myInput>
</template>
<script>
import myInput from "@/components/my-input.vue";
export default {
  components: {
    myInput
  }
}
</script>
  1. 然後,為了讓 my-input 元件可以接收來自父元件的 value 跟處理 input 事件,我們需要在 my-input 元件裡的 <input> 做兩件事
  • 將它的 value 綁定到一個名為 myValue 的 prop 上
  • 在它 input 事件被觸發時,通過 $emit 拋出新的值跟自定義的 myInput 事件
<template>
  <input 
    class="my-input"
    :value="myValue"
    @input="$emit('myInput', $event.target.value)"
    type="text" 
    placeholder="電話,例:0912-345-678"
  >
</template>
<script>
export default {
  components: {
    props: ['myValue']
  }
}
</script>
  1. 在父元件上也做兩件事
  • 通過 my-input 元件定義好的 prop,也就是 myValue,來將父元件的 value 傳入到子元件
  • 通過 my-input 元件拋出的事件,也就是 myInput,來觸發父元件的方法
<template>
  <h1>父元件</h1>
  <myInput :myValue='cellphone' @myInput="showEvent($event)">
</template>
<script>
import myInput from "@/components/my-input.vue";
export default {
  components: {
    myInput
  },
  data() {
    return {
      cellphone: null
    }
  },
  methods: {
    showEvent(event) {
      console.log(event)
    }
  }
}
</script>

要注意的是,我們在 my-input 元件是拋出 $event.target.value

@input="$emit('myInput', $event.target.value)"

所以父元件上的 $event 只是單純的 value 而已

@myInput="showEvent($event)"

  1. 若需要整個事件只要在 my-input 元件拋出 $event 就可以了
@input="$emit('myInput', $event)"

這樣父元件上的 $event 就是事件

@myInput="showEvent($event)"


上一篇
|D25| 從原始碼看 Vue 擴展 (4) - slot
下一篇
|D27| vuex 表單處理
系列文
技術在走,Vue.js 要有30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
Chris
iT邦新手 4 級 ‧ 2019-10-11 23:07:57

表單?表格?

Chris iT邦新手 4 級 ‧ 2019-10-11 23:12:06 檢舉

vuex 的文件這樣寫
https://vuex.vuejs.org/guide/forms.html#two-way-computed-property

computed: {
    message: {
        set(e){
            this.$store.commit('updateMessage', e.target.value)
        },
        get(){
            return this.$store.getters.data.message
        },
    }
}
Chris iT邦新手 4 級 ‧ 2019-10-11 23:12:41 檢舉

緊湊的寫法這樣寫

<input 
  :value="$store.getters.data.message"
  @input="$store.commit('updateMessage', $event.target.value)"
>

可以把上述的 computed 刪掉

mangoSu iT邦新手 5 級 ‧ 2019-10-11 23:49:33 檢舉

是表單才對~
抱歉~後來決定把『vuex 的 表單處理』ㄧ文移到明天發,
學習到更簡潔的寫法了~也會一起紀錄在文中~
/images/emoticon/emoticon41.gif

我要留言

立即登入留言