vue的事件注册 emit
在vue中可以通过事件的注册,在一个组件中点击,之后在另外一个组件中通过相对应的绑定,是另外一个组件页面的值进行改变
在vue使用事件注册的函数是emit
eg:
app.vue
<template>
<contations @onIncrement="increment"/>
</template>
<script>
import {ref} from "vue"
import contations from "contations.vue的路径"
export default {
name: 'App',
components: {
contations
},
setup(){
const increment =(num) =>{
xxx.value +=num;
}
return{
increment
}
}
}
</script>
contations.vue(在此页面注册事件)
<template>
<button type="button" @click="increment(1)">增</button>
<button type="button" @click="increment(-1)">减</button>
</template>
<script>
export default {
setup(props,context){
const increment = (num) => {
context.emit("OnIncrement",num);
};
return{increment};
}
}
</script>
注意事项:子集写点击事件,父级调用的时候用emit ,调用事件需要写好对应的位置
警告:[Vue warn]: Extraneous non-emits event listeners (onIncrement) were passed to component but could not be automatically inherited because component renders fragment or text root nodes. If the listener is intended to be a component custom event listener only, declare it using the "emits" option. at <ConObj onOnIncrement=fn > at <App>
解决方法:在setup之前进行声明一下,即可解决上述的警告问题
emits["Onincrement"]