Vue的v-on指令使用以及参数问题

154 阅读2分钟

在Vue中使用内置的v-on指令来绑定事件,完成对数据的更改。

1. v-on的基本使用

v-on可以绑定内置的事件,也可以绑定自定义事件【用于父子组件通信时绑定自定义事件】

1.1. 可以给同一个组件/元素绑定多个事件,各个事件分开书写。
1.2. 也可以给同一组件/元素绑定多个事件,将多个事件写成一个对象形式。
  • main.js
import { createApp} from 'vue'
import App from './App.vue'
const vm = createApp(App)
vm.mount('#app')
  • App.vue
<template>
  <h1>{{ message }}--{{ name }}</h1>
  <!-- 给同一个元素绑定多个事件,分开书写  -->
  <button @click="changeMsg" @mouseenter="changeName">改变嘻嘻</button>
  <!-- 给同一个元素绑定多个事件,写成对象形式  -->
  <button v-on="{click:changeMsg,mouseenter:changeName}">改变嘻嘻</button>
</template>

<script>
export default {
  name:'App',
  data(){
    return {
      message:'hello',
      name:'小强强'
    }
  },
  methods:{
    changeMsg(){
      this.message = 'hi'
    },
    changeName(){
      this.name = '进击的小强强'
    }
  }
}
</script>

2. v-on的参数问题

默认情况下,当绑定函数无需传递显示自定义参数时,绑定函数时可以不提供小括号。之后函数调用时vue里面会自动将event对象传递到函数里面。

<template>
  <h1>{{ message }}--{{ name }}</h1>
  <button @click="changeMsg" @mouseenter="changeName">改变嘻嘻</button>
</template>

<script>
export default {
  name:'App',
  data(){
    return {
      message:'hello',
      name:'小强强'
    }
  },
  methods:{
    changeMsg(e){
      this.message = 'hi'
      console.log(e)
    },
    changeName(e){
      this.name = '进击的小强强'
      console.log(e)
    }
  }
}
</script>

参数打印如下:

image.png

如果在绑定事件时,显示传递了参数,那么vue内部不会再自动传递事件对象到函数里面,此时无法获取到事件对象了。

<template>
  <h1>{{ message }}--{{ name }}</h1>
  <button @click="changeMsg('arg1')" @mouseenter="changeName('arg2')">改变嘻嘻</button>
</template>

<script>
export default {
  name:'App',
  data(){
    return {
      message:'hello',
      name:'小强强'
    }
  },
  methods:{
    changeMsg(arg,e){
      this.message = 'hi'
      console.log(arg,e)  // arg1 undefined
    },
    changeName(arg,e){
      this.name = '进击的小强强'
      console.log(arg,e) // arg1 undefined
    }
  }
}
</script>

此时,如果想要重新获取事件对象,需要将事件对象显示传入到函数中。

<template>
  <h1>{{ message }}--{{ name }}</h1>
  <!-- 显示传入事件对象 $event -->
  <button @click="changeMsg('arg1',$event)" @mouseenter="changeName('arg2',$event)">改变嘻嘻</button>
</template>

image.png

3. 自定义事件使用

子组件向父组件传递数据的方式之一。【子传父】
通过在子组件身上定义自定义事件,然后由子组件触发该事件,父组件就会收到来自子组件的参数,完成数据传递。【底层原因是Vue.prototype.$on收集事件,存入到事件集合中,Vue.prototype.$emit根据事件名从事件集合中触发事件】

  • App.vue
<template>
  <h1>{{ message }}--{{ name }}</h1>
  <!-- 子组件显示区域,绑定自定义事件 -->
  <Son @ownEvent="show"></Son>
</template>

<script>
import Son from './components/Son.vue'
export default {
  name:'App',
  components:{
    Son
  },
  methods:{
    show(arg){
      console.log('来自儿子参数',arg)
    }
  }
}
</script>
  • Son.vue
<template>
  <h1>我是儿子组件</h1>
  <button @click="sendArg">点击向父组件传递参数</button>
</template>

<script>
  export default{
    name:'Son',
    methods:{
      sendArg(){
      // 子组件触发自定义事件,传递参数
        this.$emit('ownEvent','子组件参数!')
      }
    }
  }
</script>