Vue学习教程-16html标签元素绑定事件

文章目录

  • 前言
  • 一、表单数据绑定事件
  • 二、多媒体元素绑定
    • 1.图片img和视频元素video
  • 三、容器元素绑定事件


前言

在Vue中,你可以通过v-on指令(或在Vue 2.x中简写为@)来绑定事件。这种方式允许你监听DOM事件,并在触发时执行一些JavaScript代码。
常见的元素主要是表单数据元素、多媒体元素和容器元素。


一、表单数据绑定事件

常见的表单数据元素
1.文本输入框元素
3. 多选框元素
4. 下拉框元素
5. 按钮元素
6. form表单元素

<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>表单元素数据绑定事件title>
   
   <script src="../js/vue.js">script>
head>
<body>
    <br><br><br>
    <div style="text-align: center;">
         <h2>xxx大学网站用户登录h2>
       div>
    <div id="root" style="text-align: center;">
         <form @submit.prevent="submitFun"  @reset="resetFun">
              用户:<input type="text" v-model.trim="userInfo.username" @input="inputFun" @blur="validateUsername"> <br/><br/>
              密码:<input type="password" v-model="userInfo.password"> <br/><br/>
              年龄:<input type="number" v-model.number="userInfo.age"> <br/><br/>
              性别:
              男<input type="radio" name="sex" v-model="userInfo.sex" value="male" @change="handleSelection"><input type="radio" name="sex" v-model="userInfo.sex" value="female" @change="handleSelection"> <br/><br/>
              爱好:
              抽烟<input type="checkbox" v-model="userInfo.hobby" value="smoke" @change="handleSelections">
              喝酒<input type="checkbox" v-model="userInfo.hobby" value="drink" @change="handleSelections">
              烫头<input type="checkbox" v-model="userInfo.hobby" value="hot-hair" @change="handleSelections">
              <br/><br/>
              所属校区
              <select v-model="userInfo.city"  @change="handleCityChange">
                   <option value="" disabled>学校所在地址option>
                   <option value="beijing">北京校区option>
                   <option value="shanghai">上海校区option>
                   <option value="shenzhen">广州校区option>
                   <option value="wuhan">深圳校区option>
              select>
              <br/><br/>
              其他信息:
              <textarea v-model.lazy="userInfo.other"  @change="saveDraft">textarea> <br/><br/>
              <input type="checkbox" v-model="userInfo.agree">阅读并接受<a href="http://www.baidu.com">《用户协议》a><br><br>
              <input type="submit" value="提交">
              <input type="reset" value="重置"><br><br>
         form>
    div>
    
body>
<script>
    Vue.config.productionTip = false //阻止提示
    // 创建实例
    const vm = new Vue({
         el:"#root",
         data(){
              return{
                   userInfo:{
				username:'',
				password:'',
				age:18,
				sex:'',
				hobby:[],
				city:'',
				other:'',
				agree:''
			}
              }
         },
         methods: {
              submitFun(){
                   console.log('输出数据...',JSON.stringify(this.userInfo))
              },
              resetFun(){
                   //重置
                   this.userInfo = {
				username:'',
				password:'',
				age:null,
				sex:'',
				hobby:[],
				city:'',
				other:'',
				agree:''
			}
                   console.log("数据清空",JSON.stringify(this.userInfo));
                   
              },
              inputFun(element){
                   console.log("实时输出:",element.target.value);
              },

              validateUsername() {
                   console.log("input 获取焦点 ");
              },
              saveDraft(){
                   console.log("保存数据...");
                   
              },
              handleSelection() {
                   console.log('性别选中值:', this.userInfo.sex)

              },
              handleSelections(){
                   console.log("爱好选中值",this.userInfo.hobby);
                   
              },
              handleCityChange(){
                   console.log("城市选中",this.userInfo.city);
                   
              },
        
         },
         

    })
script>

二、多媒体元素绑定

1.图片img和视频元素video

<head>
   <meta charset="UTF-8" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0" />
   <title>多媒体元素与事件绑定title>
   <script src="../js/vue.js">script>
 head>
 <body>
    <div id="root">
         
          
         <div>
           <img 
             :src="imageUrl"
             @load="onImageLoaded"
             @error="onImageError"
             alt="示例图片"
           >
         div>

         
         <video 
         ref="videoPlayer"
         :src="videoUrl"
         @play="onVideoPlay"
         @pause="onVideoPause"
         @timeupdate="onTimeUpdate"
         @ended="onVideoEnd"
         controls
       >video>
       
       <button @click="togglePlay">
         {{ isPlaying ? '暂停' : '播放' }}
       button>
       <input 
         type="range" 
         v-model="playbackRate"
         min="0.5" 
         max="2" 
         step="0.1"
         @input="updatePlaybackSpeed"
       >


    div>

 body>
 <script>
   Vue.config.productionTip = false; //阻止提示
   // 创建实例
   const vm = new Vue({
     el: "#root",
     data() {
       return {
         imageUrl: 'https://img2.baidu.com/it/u=3933934708,2924683722&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=667',
         videoUrl: './demo.mp4',
         isPlaying: false,
         playbackRate: 1,
         currentTime: 0

       };
     },
     methods: {
       
       onImageLoaded(e) {
         console.log('图片加载成功', e.target.naturalWidth)
         // 记录图片尺寸
         this.$emit('loaded', {
           width: e.target.width,
           height: e.target.height
         })
       },
       onImageError() {
         console.error('图片加载失败')
         // 显示备用图片
         this.imageUrl = 'https://pic.rmb.bdstatic.com/bjh/250110/dump/0a387e68a27a957cbae3d5ae5071427a.jpeg'
       },
      
     },
   });
 script>

三、容器元素绑定事件

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>容器元素与事件绑定title>
  <script src="../js/vue.js">script>
  <style>
    
      .scroll-container {
        /* 容器尺寸 */
        width: 300px;
        height: 200px;

        /* 滚动条核心设置 */
        overflow: auto; /* 或 overflow-y: scroll */

        /* 样式增强 */
        border: 1px solid #ccc;
        padding: 10px;
      }

      /* 内容区 */
      .content {
        width: 1000px;  /* 超过容器宽度 */
        height: 800px;  /* 超过容器高度 */
      }
  style>
head>
<body>
   <div id="root">
        
        <div class="scroll-container"
          @click="handleClick"
          @dblclick="handleDoubleClick"
          @mouseenter="handleMouseEnter"
          @mouseleave="handleMouseLeave"
          @scroll.passive="handleScroll">
          <div class="content">
            
            这是一个会触发滚动条的示例内容...
          div>
        div>

   div>

body>
<script>
 Vue.config.productionTip = false; //阻止提示
 // 创建实例
 const vm = new Vue({
   el: "#root",
   data() {
     return {
       videoUrl: './demo.mp4',
       isPlaying: false,
       playbackRate: 1,
       currentTime: 0
     };
   },
   methods: {
     handleClick(e) {
       console.log('点击位置:', e.clientX, e.clientY)
       this.$emit('container-click', e)
     },
     handleDoubleClick() {
       console.log('双击事件')
     },
     handleMouseEnter() {
       console.log('鼠标进入')
     },
     handleMouseLeave() {
       console.log('鼠标离开')
     },
     handleScroll(e) {
       console.log('滚动位置:', e.target.scrollTop)
     },
     togglePlay() {
       const player = this.$refs.videoPlayer
       this.isPlaying ? player.pause() : player.play()
     },
     onVideoPlay() {
       this.isPlaying = true
       console.log('视频开始播放')
     },
     onVideoPause() {
       this.isPlaying = false
       console.log('视频暂停')
     },
     onTimeUpdate(e) {
       this.currentTime = e.target.currentTime
       console.log('播放进度:', this.currentTime)
     },
     onVideoEnd() {
       console.log('播放结束')
       this.isPlaying = false
     },
     updatePlaybackSpeed() {
       this.$refs.videoPlayer.playbackRate = this.playbackRate
     }
        
   },
 });
script>

你可能感兴趣的:(vue.js,学习,前端)