前端技术

Vue function and event object

2018-07-23  本文已影响15人  剑有偏锋

一 创建测试项目

vue init webpack-simple vuedemo

二 进入demo目录

cd vuedemo

三 安装依赖

cnpm install

四 修改代码App.vue

<template>
  <div id="app">
    <h2>{{msg}}</h2>
    
    <h2>1 v-on:click  and  Shorthand @click</h2>

    <button v-on:click="run1()">run a event one</button>
    <button @click="run2()">run a event two</button>
<br>
<br>

 <h2>2 use function  to get and set data in data()  </h2>
     <button @click="getMsg()">get msg in data</button>
  
     <button @click="setMsg()">set msg in data</button>
  
  <br>
  <br>
     <button @click="requestData()">requestData</button>
  <ul>
     <li v-for="(item, key) in list" :key="item.id"> 
       {{key}} --- {{item}}
     </li>
  </ul>

<h2>3 function with param</h2>
   <button @click="deleteData('111')">deleteData fuction with param</button>

<h2>4 function with event object param, and get dataset aid</h2>
   <button data-aid='123' @click="eventFn($event)">event object</button>


  </div>
</template>

<script>
export default {
  name: "app",
  data() {
    return {
      msg: "Welcome to Your Vue.js App",
      list: []
    };
  },
  methods: {
    run1: function() {
      console.log("run a event one");
      alert("run a event one");
    },

    run2() {
      console.log("run a event two");
      alert("run a event two");
    },
    getMsg() {
      console.log(this.msg);
      alert(this.msg);
    },
    setMsg() {
      this.msg = "i change msg";
    },
    requestData() {
      for (var i = 0; i < 10; i++) {
        this.list.push("i am the " + i + " data");
      }
    },
    deleteData(val) {
      alert(val);
    },
    eventFn(e) {
      console.log(e);

      e.target.style.background = "red";
      console.log(e.target.dataset.aid);
    }
  }
};
</script>

<style>
</style>

五 运行

npm run dev


image.png

六 总结

1 控件事件监听v-on:click及其简写@click
2 function传参调用,传字符串和事件
3 从事件参数获取,dom控件对象数据集aid

七 参考

https://cn.vuejs.org/v2/guide/syntax.html#v-on-%E7%BC%A9%E5%86%99
https://cn.vuejs.org/v2/guide/events.html

上一篇下一篇

猜你喜欢

热点阅读