zoukankan      html  css  js  c++  java
  • NO.08--VUE之自定义组件添加原生事件

    前几篇给大家分享了我的业余的“薅羊毛”的经历,回归正题,讲回vue吧:

    许多vue新手在工作开发中会遇到一个问题,直接使用 button 添加原生事件是没有问题的,但是使用自定义组件添加原生事件时,就会发现添加不上。比如我写了两个 button,一个点击让 div 变红,一个点击让 div 变蓝。

    App.vue文件

    <template>
      <div id="app">
        <button @click="changeRed">变红</button>
        <!-- 使用 Btn 组件  并添加原生事件 -->
        <Btn @click="changeBlue"></Btn>
        <div :class="box"></div>
      </div>
    </template>
    
    <script>
    // 引入 Btn 这个组件
    import Btn from './assets/components/Btn.vue'
    export default {
      name: 'app',
      data () {
        return {
          box: 'yellow'
        }
      },
      methods: {
        changeRed(){
          this.box = 'red'
        },
        changeBlue(){
          this.box = 'blue'
        }
      },
      // 组件 注册
      components: {
        Btn
      }
    }
    </script>
    
    <style>
    .yellow{
       200px;
      height: 200px;
      background: #ff0;
    }
    .red{
       200px;
      height: 200px;
      background: #f00;
    }
    .blue{
       200px;
      height: 200px;
      background: #00f;
    }
    </style>
    
    

    Btn.vue 文件

    <template>
        <div class="btn">
            <button>变蓝</button>
        </div>
    </template>
    
     
    点击变色.gif

    会发现 Btn 的绑定事件无效。其实 vue 官方是有提供对应的方法的, 给组件绑定原生事件,就是在自定义组件 Btn 的原生事件后面加个 .native 后缀就好了。

    App.vue文件

    <template>
      <div id="app">
        <button @click="changeRed">变红</button>
        <!-- 使用 Btn 组件  并添加事件 -->
        <Btn @click.native="changeBlue"></Btn>
        <div :class="box"></div>
      </div>
    </template>
    

    效果:


     
    点击变色-1.gif
  • 相关阅读:
    <q>标签,短文本引用
    使用<span>标签为文字设置单独样式
    html速查表
    禁用第三方键盘
    画虚线的方法 (记录)
    渐变色以及隐藏输入框光标
    iOS9 网络适配
    iOS 截屏/将图片存储到相册或沙盒目录下
    从任意字符串中获取所有的数字
    IOS开发
  • 原文地址:https://www.cnblogs.com/cb-bin/p/8734330.html
Copyright © 2011-2022 走看看