在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"]