vue 이벤트 바인딩, 이벤트 매개변수, 이벤트 수정자, 양식 양방향 바인딩, 리스너, 계산된 속성

목차

이벤트 바인딩

이벤트 매개변수

이벤트 수정자

형태

watch(청취자 청취 속성)

계산됨(계산된 속성)

인터뷰 질문들


이벤트 메커니즘

개요 DOM 단계에서는 이벤트 메커니즘의 특징을 설명했습니다.

  1. 사건의 세 가지 요소

  2. 이벤트 바인딩

  3. 이벤트 스트림

  4. 이벤트 객체

  5. 이벤트 에이전트

  6. 이벤트 유형의 개념은 Vue에 여전히 존재하지만 Vue의 이벤트 메커니즘은 더 간단하고 편리합니다.

이벤트 바인딩

v-on 지시문을 사용하여 DOM 이벤트를 수신하고 트리거될 때 일부 JavaScript 코드를 실행할 수 있습니다. v-on은 호출해야 하는 메소드 이름도 수신할 수 있습니다. <button v-on:click="handler">good</button>메소드: { handler: function (event) { if (event) { Alert(event.target.tagName) } // event네이티브 DOM 이벤트입니다} } 메소드에 직접 바인딩되는 것 외에도 다음에서 메소드를 호출할 수도 있습니다. 인라인 JavaScript $<button v-on:click="say('hi',$event)">Say hi</button>:methods: { say: function (message,event) { Alert(message) } } 이벤트 바인딩이 vue에서 사용될 가능성이 높으므로 약어 형식 <button @click= "가 여기에 제공됩니다. say('hi',$event)">안녕하세요</button>

이벤트 매개변수

이벤트가 호출되면 매개변수가 전달될 수 있습니다.
 

<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>

이벤트를 바인딩할 때 v-on: 이벤트 이름을 @event name 으로 축약 할 수 있습니다 . 이 방법이 자주 사용됩니다.

이벤트 수정자

이벤트 수정자 이벤트 핸들러에서 event.preventDefault() 또는 event.stopPropagation()을 호출하는 것은 매우 일반적인 요구 사항입니다. Vue는 더 나은 방법을 제공합니다. 이벤트 처리 기능에는 DOM 이벤트 세부 정보를 처리하는 대신 순수한 데이터 로직만 있으며 이러한 세부 정보는 이벤트 수정자를 통해 완료됩니다.

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

일반적인 수정자는 다음과 같습니다.stop 이벤트 버블링을 중지합니다.prevent가 이벤트 기본 동작을 방지합니다.capture는 이벤트 캡처 단계에서 이벤트 처리 기능을 실행합니다.self 처리 기능은 event.target이 현재 요소 자체일 때만 트리거됩니다.once 이벤트 이후 처리 기능은 한 번 실행됩니다. .passive 스크롤 이벤트 바인딩을 해제하는 기본 동작(예: 스크롤 동작)이 즉시 트리거됩니다. 일반적으로 스크롤과 함께 사용되며 이는 모바일 단말기의 성능을 향상시킬 수 있습니다. 키 수정자는 일반적으로 다음에서 사용됩니다. keyup 이벤트 유형과 결합 Enter, .tab, .delete, .esc , .space, .up, .down, .left, .right .ctrl, .alt, .shift, .meta 마우스 수정자 mouseup 이벤트 .left, . 오른쪽, .가운데

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>

형태

v-model 지시문을 사용하여 <input>양식 <textarea><select>요소에 대한 양방향 데이터 바인딩을 만들 수 있습니다 . 컨트롤 유형에 따라 요소를 업데이트하는 올바른 방법을 자동으로 선택합니다. 그 마법에도 불구하고 v-model은 본질적으로 구문상의 설탕입니다. 사용자 입력 이벤트를 수신하여 데이터를 업데이트하고 일부 극단적인 시나리오에 대한 특수 처리를 수행하는 역할을 담당합니다. v-model을 사용하여 값을 바인딩하면 이름 속성을 작성할 필요가 없습니다.


<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(청취자 청취 속성)

리스너를 사용하는 것은 데이터가 변경될 때 비동기식 또는 비용이 많이 드는 작업을 수행해야 할 때 가장 유용합니다.

대부분의 경우 계산된 속성이 더 적합하지만 때로는 사용자 정의 리스너가 필요할 수도 있습니다. 이것이 Vue가 watch 옵션을 통해 데이터 변경에 응답하는 보다 일반적인 방법을 제공하는 이유입니다. 이 접근 방식은 데이터가 변경될 때 비동기식 또는 비용이 많이 드는 작업을 수행 해야 할 때 가장 유용합니다 .


<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>

계산됨(계산된 속성)

계산된 속성에 대한 종속성이 있는 데이터

계산된 속성은 변수가 일부 계산을 거친 후 직접 출력되는 대신 출력되도록 할 때 사용할 수 있습니다. 계산된 속성은 응답 종속성에 따라 캐시됩니다. 연관된 반응적 종속성이 변경될 때만 재평가됩니다. 함수를 호출할 때마다 함수가 다시 실행됩니다.


<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: {}
    })

인터뷰 질문들



watch와 계산 의 차이점은
   무엇입니까? 계산된 속성은 특정 속성의 변경을 계산합니다
    . 특정 값이 변경되면 계산된 속성이 모니터링되어
watch
   1로 반환됩니다. 값의 변경을 모니터링하고 비동기 작업을 수행합니다. [axios request]
   '$route.query': {        this.loadArticle()    }    2. 캐싱하지 않고 현재 값이 발생할 때만 실행/변경될 때만 응답



추천

출처blog.csdn.net/qq_53866767/article/details/131883201