【Vue3】v-on使用者事件

Vue3

【Vue3】v-on使用者事件

Vue3


效果切換按鈕

1
2
3
4
<div id="app">
  <div class="box" :class="{ rotate : isTransform }"></div>
  <button type="button" @click="changeClass">按鈕</button>
</div>

1
2
3
4
5
6
7
8
.box{
  width: 40px;
  height: 40px;
  border: solid 1px #cccccc;
}
.rotate{
  transform: rotate(45deg);
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
Vue.createApp({
  data(){
    return{
      isTransform: true
    }
  },
  methods:{
    changeClass(){
      this.isTransform = !this.isTransform;
    }
  }
}).mount("#app");


效果切換按鈕(帶參數)

1
2
3
4
<div id="app">
  <div class="box" :class="{ rotate : isTransform }"></div>
  <button type="button" @click="changeClass('isTransform')">按鈕</button>
</div>

1
2
3
4
5
6
7
8
.box{
  width: 40px;
  height: 40px;
  border: solid 1px #cccccc;
}
.rotate{
  transform: rotate(45deg);
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
Vue.createApp({
  data(){
    return{
      isTransform: true
    }
  },
  methods:{
    changeClass(item){
      this[item] = !this[item];
    }
  }
}).mount("#app");


驗證表單+事件綁定在表單本身上

1
2
3
4
5
6
<div id="app">
  <form @submit.prevent="submitForm">
    <input type="text">
    <button>按鈕</button>
  </form>
</div>

1
2
3
4
5
6
7
Vue.createApp({
  methods:{
    submitForm(){
      console.log("表單已送出")
    }
  }
}).mount("#app");

只有綁定@submit會有表單原生的轉跳事件,需要使用.prevent


動態事件

1
2
3
<div id="app">
  <button type="button" @[event]="dynamicEvent">按鈕</button>
</div>

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
Vue.createApp({
  data(){
    return{
      event: "click"
    }
  },
  methods:{
    dynamicEvent(){
      console.log("這是一個動態事件")
    }
  }
}).mount("#app");


動態物件方法

1
2
3
4
5
6
<div id="app">
  <button type="button" @="{
    mousedown: down,
    mouseup: up
  }">按鈕</button>
</div>

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
Vue.createApp({
  methods:{
    down(){
      console.log("按下");
    },
    up(){
      console.log("放開")
    }
  }
}).mount("#app");

當按下按鈕時不放,出現"按下";鬆開滑鼠左鍵後,出現"放開"

Vue3 

其他相關