iT邦幫忙

2023 iThome 鐵人賽

DAY 15
0
Vue.js

重新瞭解vue3.js + vite框架系列 第 15

Day15-v-on 事件觸發

  • 分享至 

  • xImage
  •  

15-0 js

const App = {
  data() {
    return {
      name: '小明',
      isTransform: true,
      num: 10,
      event: 'click'
    }
  },
  methods: {
    // 轉換按鈕事件
    changeClass() {
      this.isTransform = !this.isTransform;
    },
    // 帶入參數事件
    change(key) {
      this[key] = !this[key];
    },
    onChange(evt) {
      console.log('change事件',evt)
    },
    submitForm() {
      console.log('表單已送出', `name 為 ${this.name}`)
    },
    dynamicEvent() {
      console.log('這是一個動態事件', this.event)
    },
    down() {
      console.log('按下');
    },
    up() {
      console.log('放開');
    },
    double(n) {
      return `NT$ ${n * 2}`;
    },
  }
};

Vue.createApp(App).mount('#app');

15-1 觸發事件 與 帶入參數

  <div class="box" :class="{ rotate: isTransform }"></div>
  <hr>
  <!-- 綁定資料的值觸發changeclass事件 -->
  <button class="btn btn-outline-primary" v-on:click="changeClass">選轉物件</button>
  
   <!-- 使用change方法傳入參數執行事件 -->
  <button class="btn btn-outline-primary" v-on:click="change('isTransform')">選轉物件</button>

15-2 input change 事件

  <input type="text" @change="onChange">

15-3 form submit 事件

  <!-- 原生Html事件按送出時會重新整理,預防此事件需加入修飾符.prevent -->
  <!-- 不設定在按鈕即可觸發事件,可至直接鍵盤按enter亦可觸發 -->
  <form @submit.prevent="submitForm">
    <input type="text" v-model="name">
    <button>送出表單</button>
  </form>

15-4 動態事件 []

  <input type="text" @[event]="dynamicEvent">
  <input type="text" v-model="event">

15-5 動態物件方法 {}

  <!-- 此方法無法傳入參數 -->
  <button class="box" @="{
    mousedown:down,
    mouseup:up
  }">
  </button>

https://ithelp.ithome.com.tw/upload/images/20230930/20121669k3H9UG9frm.png
https://ithelp.ithome.com.tw/upload/images/20230930/20121669tHdzzaH8TF.png

.
.
知識點來源:六角課程

以上是今天所提供知識點如有誤,再請務必在下面留言~


上一篇
Day14-v-model 修飾符
下一篇
Day16-v-on 修飾符
系列文
重新瞭解vue3.js + vite框架30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言