我想将事件从子评论传递给父评论。 我在 vue2 中做了同样的事情,但我不知道如何在 vue3 中做到这一点。
这是子组件设置方法。
setup(props, { emit }) {
const router = useRouter();
const form = ref(
{
email: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="50313a312910373d31393c7e333f3d" rel="noreferrer noopener nofollow">[email protected]</a>",
password: "123456789",
isLoading: false,
},
);
const user = ref("");
const error = ref("");
function login() {
User.login(this.form).then(() => {
emit('login', true);
// this.$root.$emit("login", true); -- vue2
localStorage.setItem("auth", "true");
router.push('/dashboard');
})
.catch(error => {});
}
return { form, login, user, error};
}
从这里发出登录方法,我想听家长评论。
这是父组件,emit.on 方法在这里不起作用
setup(props, { emit }) {
const router = useRouter();
const state = reactive({
isLoggedIn: false,
});
onMounted(async () => {
emit.on("login", () => { // `vue2` this.$root.$on("login"`
this.isLoggedIn = true;
});
});
最佳答案
在父组件中,您应该为该发出的事件添加一个处理程序:
<child @login="onLogin"></child>
setup(props, { emit }) {
const router = useRouter();
const state = reactive({
isLoggedIn: false,
});
function onLogin(){
state.isLoggedIn=true,
}
return{state,onLogin}
}
或者在单独的文件中创建一个名为 useAuth
的可组合函数:
import {reactive} from 'vue'
const state = reactive({
isLoggedIn: false,
});
const useAuth=()=>{
function onLogin(){
state.isLogged=true;
}
return {state,onLogin}
}
export default useAuth();
然后在两个组件中导入函数:
child :
import useAuth from './useAuth'
....
setup(props, { emit }) {
const router = useRouter();
const {useAuth} =useAuth();
....
function login() {
User.login(this.form).then(() => {
onLogin() //will call the nested function that set loggedIn to true
localStorage.setItem("auth", "true");
router.push('/dashboard');
})
.catch(error => {});
}
在父级中:
import useAuth from './useAuth'
....
setup(props, { emit }) {
const router = useRouter();
const {state} =useAuth();
//it replaces your local state
关于laravel - 如何在vue3中监听父组件中的emit事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65434526/