$event
<body>
<div id="app">
<input type="text" @click="abc($event)" value="123" />
</div>
<script>
var vm = new Vue({
el: "#app",
data: {},
methods: {
abc(event) {
console.log(event.target.value);
}
}
});
</script>
</body>
The output result is: 123
When we print event
this parameter, we can see many attributes. Which target
represents the element that triggered the event.
In the target
middle there are a number of properties, we can find it. For example, when you need to get the id, you can also event.target.id
get the text content of the p tag event.target.innerText
.
<div id="app">
<button v-on:click="click">click me</button>
</div>
...
var app = new Vue({
el: '#app',
methods: {
click(event) {
console.log(typeof event); // object
}
}
});
Briefly summarize its usage:
-
Using the form without parentheses, the event object will be automatically passed as an argument;
-
To use the form with parentheses, we need to use the $event variable to explicitly pass in the event object.
And event.currentTarget
are you bind event elements, usually have the following usage.
#获得点击元素的前一个元素
e.currentTarget.previousElementSibling.innerHTML
#获得点击元素的第一个子元素
e.currentTarget.firstElementChild
# 获得点击元素的下一个元素
e.currentTarget.nextElementSibling
# 获得点击元素中id为string的元素
e.currentTarget.getElementById("string")
# 获得点击元素的string属性
e.currentTarget.getAttributeNode('string')
# 获得点击元素的父级元素
e.currentTarget.parentElement
# 获得点击元素的前一个元素的第一个子元素的HTML值
e.currentTarget.previousElementSibling.firstElementChild.innerHTML
$emit(event,xargs)
vm.emit (event, arg) // Trigger the event on the current instance vm.emit( event, arg) // Trigger the event on the current instance vm.on( event, fn ); // Run fn after monitoring the event event;
For example: subcomponent:
<template>
<div class="train-city">
<h3>父组件传给子组件的toCity:{
{sendData}}</h3>
<br/><button @click='select(`大连`)'>点击此处将‘大连’发射给父组件</button>
</div>
</template>
<script>
export default {
name:'trainCity',
props:['sendData'], // 用来接收父组件传给子组件的数据
methods:{
select(val) {
let data = {
cityname: val
};
this.$emit('showCityName',data);//select事件触发后,自动触发showCityName事件
}
}
}
</script>
Parent component:
<template>
<div>
<div>父组件的toCity{
{toCity}}</div>
<train-city @showCityName="updateCity" :sendData="toCity"></train-city>
</div>
<template>
<script>
import TrainCity from "./train-city";
export default {
name:'index',
components: {TrainCity},
data () {
return {
toCity:"北京"
}
},
methods:{
updateCity(data){//触发子组件城市选择-选择城市的事件
this.toCity = data.cityname;//改变了父组件的值
console.log('toCity:'+this.toCity)
}
}
}
</script>
The receiving function defined in the parent component value is defined by the trigger function defined in the child component. For example, the @input of the child component will call $emit() for every input, that is, the function in the parent component will also be called