vue event binding, event parameters, event modifiers, form two-way binding, listeners, calculated properties

Table of contents

event binding

event parameters

event modifier

form

watch (listener listening attribute)

computed (computed property)

Interview questions


event mechanism

Overview In the dom stage, we have described the characteristics of the event mechanism:

  1. three elements of event

  2. event binding

  3. event stream

  4. event object

  5. event agent

  6. The concepts of event types still exist in Vue, but the event mechanism in Vue is simpler and more convenient.

event binding

You can use the v-on directive to listen for DOM events and run some JavaScript code when triggered. v-on can also receive a method name that needs to be called. <button v-on:click="handler">good</button>methods: { handler: function (event) { if (event) { alert(event.target.tagName) } // eventIt is a native DOM event} } In addition to being directly bound to a method, you can also call methods in inline JavaScript statements , $pass the native event object through <button v-on:click="say('hi',$event)">Say hi</button>event: methods: { say: function (message,event) { alert(message) } } Since event binding is more likely to be used in vue, the abbreviation form <button @click=" is provided here. say('hi',$event)">Say hi</button>

event parameters

When the event is called, parameters can be passed:
 

<div id="app">
        <el-button @click="toAdd" type="primary" size="small">新增</el-button>
        <div>
            <el-table type="index" size="small" :data="tableData" style="width: 50%">
                <el-table-column  prop="date" label="日期" width="180">
                </el-table-column>
                <el-table-column prop="name" label="姓名" width="180">
                </el-table-column>
                <el-table-column prop="address" label="地址">
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button size="small" @click="toEdit(scope.row)" type="primary">编辑</el-button>
                        <el-button size="small" type="danger" @click="toDelete(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-dialog :title="title" :visible.sync="dialogFormVisible">
            <el-form :model="form">
                <el-form-item  label="时间" :label-width="formLabelWidth">
                    <el-input v-model="form.date" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="姓名" :label-width="formLabelWidth">
                    <el-input v-model="form.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="地址" :label-width="formLabelWidth">
                    <el-input v-model="form.address" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
            </div>
        </el-dialog>
    </div>

<script>
        new Vue({
            el: "#app",
            data: {
                dialogFormVisible: false,
                formLabelWidth: "120px",
                form: {},
                title: '',
                tableData: [{
                    id: 1,
                    date: '2016-05-02',
                    name: '王小虎',
                    address: '上海市普陀区金沙江路 1518 弄'
                }, {
                    id: 2,
                    date: '2016-05-04',
                    name: '王小虎',
                    address: '上海市普陀区金沙江路 1517 弄'
                }, {
                    id: 3,
                    date: '2016-05-01',
                    name: '王小虎',
                    address: '上海市普陀区金沙江路 1519 弄'
                }, {
                    id: 4,
                    date: '2016-05-03',
                    name: '王小虎',
                    address: '上海市普陀区金沙江路 1516 弄'
                }]
            },
            methods: {
                toAdd() {
                    this.dialogFormVisible = true;
                    this.form = {};
                    this.title = '新增数据'
                },
                toEdit(row) {
                    this.form = { ...row };
                    this.dialogFormVisible = true;
                    this.title = '修改数据';
                },
                toDelete(id) {
                    this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.tableData.splice(id,1)
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });
                }
            }
        })
    </script>

When binding events, you can abbreviate v-on: event name to @event name . This method is often used:

event modifier

Event Modifiers It is a very common requirement to call event.preventDefault() or event.stopPropagation() in an event handler. Vue provides a better way: the event handling function only has pure data logic, instead of dealing with DOM event details, these details are completed through event modifiers.

<button v-on:click.prevent="handler">点我点我</button>

Common modifiers are as follows.stop stops event bubbling.prevent prevents event default behavior.capture executes the event processing function in the event capture phase.self The processing function is only triggered when event.target is the current element itself.once After the event processing function is executed once The default behavior of unbinding the .passive scroll event (i.e. scrolling behavior) will be triggered immediately. It is generally used in conjunction with scroll, which can improve the performance of the mobile terminal. Key modifiers are generally used in conjunction with keyup event types. enter, .tab, .delete, .esc , .space, .up, .down, .left, .right .ctrl, .alt, .shift, .meta mouse modifier mouseup event .left, .right, .middle

new Vue({
      el: "#app",
      data: {
        msg: '事件修饰符'
      },
      methods: {
        keyupHandle() {
          console.log('按下某些特殊键');
        },
        toJump() {
          console.log('跳转');
          alert(1);
        },
        outer(e) {
          // e.target是触发事件的源头元素,目标元素
          // e.currentTarget 当前执行事件处理程序的元素,当前目标元素
          // console.log('outer', e.target, e.currentTarget);
          console.log('outer')
          for (let i = 0; i < 100; i++) {
            console.log(i);
          }
        },
        inner(e) {
          // e.stopPropagation();
          // console.log('inner', e.target, e.currentTarget);
          console.log('inner');
        }
      }
    })
<div id="app">
    <!-- <input type="text" @keyup.enter="keyupHandle"> -->
    <input type="text" @keyup.13="keyupHandle">
    <!-- <input type="text" @mouseup.left="keyupHandle"> -->
    {
   
   {msg}}
    <a @click.prevent="toJump" href="http://www.baidu.com">百度一下</a>
    
    <!-- 点击inner   event.target   -->
    <!-- <div class="outer" @click.self.once="outer"> -->
    <!-- <div class="outer" @click.self="outer"> -->
    <!-- <div class="outer" @click.capture="outer"> -->
    <div class="outer" @scroll.passive="outer">
      outer
      <div class="inner" @click="inner">
        <!-- <div class="inner" @click.stop="inner"> -->
        inner
      </div>
    </div>
  </div>

form

You can use the v-model directive to create two-way data binding<input> on forms , <textarea>and <select>elements . It automatically chooses the correct method to update the element based on the control type. Despite its magic, v-model is essentially syntactic sugar. It is responsible for listening to user input events to update data and perform some special processing for some extreme scenarios. If the value is bound using v-model, then the name attribute does not need to be written.


<div id="app">
    {
   
   {msg}}
    <br>
    {
   
   {stu}}
    <br>
    <!-- 用户名:<input type="text" v-model.lazy="stu.username"> -->
    用户名:<input type="text" v-model.trim="stu.username">
    <br>
    <!-- .number修饰符,可以将采集到的数据转为number类型,然后再存储到数据模型中 -->
    年龄:<input type="text" v-model.number="stu.age">
    <br>
    <!-- 性别 -->
    性别:<input type="radio" value="male" v-model="stu.gender">男
    <input type="radio" value="female" v-model="stu.gender">女
    <br>
    <!-- 爱好 -->
    爱好:<input type="checkbox" value="basketball" v-model="stu.hobby">篮球
    <input type="checkbox" value="swimming" v-model="stu.hobby">游泳
    <input type="checkbox" value="dancing" v-model="stu.hobby">跳舞
    <br>
    <!-- 城市 -->
    城市:
    <!-- <select multiple v-model="stu.city"> -->
    <select v-model="stu.city">
      <option value="shanghai">上海</option>
      <option value="beijing">北京</option>
      <option value="guangzhou">广州</option>
    </select>
    <br>
    <!-- 简介 -->
    简介:<textarea v-model="stu.info" cols="30" rows="10"></textarea>
  </div>
### js代码
    new Vue({
      el: '#app',
      data: {
        msg: 'hello',
        stu: {
          // 复选框
          hobby: []
        }
      },
      methods: {}
    })
​

watch (listener listening attribute)

Using listeners is most useful when you need to perform asynchronous or expensive operations when data changes

While computed properties are more appropriate in most cases, sometimes a custom listener is needed. This is why Vue provides a more general way to respond to data changes through the watch option. This approach is most useful when you need to perform asynchronous or expensive operations when data changes .


<div id="app">
    {
   
   {msg}}
    <br>
    a:<input type="text" v-model.number="a">
    <br>
    +
    <br>
    b:<input type="text" v-model.number="b">
    <br>
    =
    <br>
    <output>{
   
   {total}}</output>
  </div>

 new Vue({
      el: '#app',
      data: {
        msg: 'hello',
        a: 0,
        b: 0,
        total: 0
      },
      methods: {},
      // 监听  侦听
      watch: {
        a(newValue, oldValue) {
          this.total = this.a + this.b;
        },
        b(newValue, oldValue) {
          this.total = this.b + this.a;
        }
      }
    })
//深度监听

 new Vue({
      el: '#app',
      data: {
        msg: 'hello',
        a: 1,
        obj: {
          name: 'zhangsan',
          age: 12
        },
      },
      watch: {
        a(newValue, oldValue) {
          console.log('a数据发生变化...');
        },
        /* obj(newValue, oldValue) {
          console.log('obj数据发生变化...');
        } */
        // 深度监听
        obj: {
          handler(newValue, oldValue) {
            console.log('obj数据发生变化...');
          },
          // 深度监听
          deep: true
        }
      },
      methods: {
        changeObj() {
          // 更改内部数据
          this.obj.name = 'lisi';
        }
      }
    })

 <div id="app">
    {
   
   {msg}}
    <br>
    {
   
   {obj}}
    <button @click="changeObj">更改obj</button>
  </div>

computed (computed property)

Data with dependencies on computed properties

Computed properties can be used when we want a variable to undergo some calculation and then be output rather than output directly. Computed properties are cached based on their responsive dependencies. They are only re-evaluated when the associated reactive dependencies change. Each call to the function will cause the function to be re-executed.


<div id="app">
    {
   
   {msg}}
    <br>
    a:<input type="text" v-model.number="a">
    <br>
    +
    <br>
    b:<input type="text" v-model.number="b">
    <br>
    =
    <br>
    {
   
   {total}}
  </div>   
    new Vue({
      el: '#app',
      data: {
        msg: 'hello',
        a: 0,
        b: 0,
        // total: 0
      },
      // 计算属性
      computed: {
        total(){
            console.log('计算属性');
            // return 111
            return this.a+this.b
        }
      },
      methods: {}
    })

Interview questions


What is the difference between watch and computed?
computed
   1. It is cacheable. The value does not change when the page is re-rendered. The calculated attribute will immediately return the previous calculation result without having to execute the function again. 2. The calculated attribute calculates the
    change of a certain attribute. If a certain value Changed, the calculated attribute will be monitored and returned to
watch
   1. Monitor the change of the value and perform an asynchronous operation [axios request]
   '$route.query':{        this.loadArticle()    }    2. No caching, only when the current value occurs Will be executed/ response



Guess you like

Origin blog.csdn.net/qq_53866767/article/details/131883201