iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 6
0
自我挑戰組

新手初探 Vue系列 第 6

鐵人賽Day06 - v-on 綁定頁面行為

接下來要來介紹,如何綁定事件,以 click 事件來舉例:

<div id="app">
  <input type="text" class="form-control" v-model="text">
  <button class="btn btn-primary mt-1">反轉字串</button>
  <div class="mt-3">
    {{ newText }}
  </div>
</div>

<script>
var app = new Vue({
  el: '#app',
  data: {
    text: '',
    newText: ''
  },
});
</script>

先在 input 欄位內綁定 datatext 變數
newText 變數先定義起來放置在頁面上

而現在要做的是點擊 button 元素時,會把輸入在 input 欄位內的文字做反轉
這時候會產生 click 事件,我們就可以利用 v-on 指令綁定在 button 元素上
click 事件會觸發的 function 則寫在另外的 methods 內,如下:

<div id="app">
  <input type="text" class="form-control" v-model="text">
  <button class="btn btn-primary mt-1" v-on:click="reverseText">反轉字串</button>
  <div class="mt-3">
    {{ newText }}
  </div>
</div>

<script>
var app = new Vue({
  el: '#app',
  data: {
    text: '',
    newText: ''
  },
  methods: {
      reverseText: function(){
          consle.log('HELLO');
      }
  }
});
</script>

與以往不同的是,Vue 的結構不再只有 eldata 還多了 methods,事件觸發的 function 就定義在這裡面
button 元素綁定 v-on 指令且為 click 事件,值則為觸發的 function 名字
這時候我們可以用 console 來檢查一下,是否為正確執行

正確執行之後我們可以針對反轉字串的相關方法寫進去 function 內:

<script>
var app = new Vue({
  el: '#app',
  data: {
    text: '',
    newText: ''
  },
  methods: {
      reverseText: function(){
          this.newText = this.text.split('').reverse().join('');
      }
  }
});
</script>

比較值得注意的是,如果我們要讀取 data 內的資料時,需使用 this 這個關鍵字,再讀取他們的屬性
至於 .split('').reverse().join(''); 就是反轉字串的方法


上一篇
鐵人賽Day05 - v-for & v-if
下一篇
鐵人賽Day07 - 修飾符
系列文
新手初探 Vue30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言