点击按钮切换v-navigation-drawer内容时避免抽屉关闭的问题
你的问题核心在于v-navigation-drawer的temporary属性——这个属性会让抽屉在点击页面非抽屉区域时自动关闭。当你点击第二个按钮时,虽然执行了changeContent切换内容,但同时触发了temporary的关闭逻辑,导致抽屉被立刻关闭。另外你的data定义不符合Vue规范,变量没有放在return中,无法实现正确的响应式绑定。
方案1:移除temporary属性(不需要点击外部关闭抽屉)
直接去掉temporary,抽屉只会通过第一个按钮的drawerTest变量控制开关,点击其他元素不会触发关闭:
<template> <div> <v-btn @click="drawerTest = !drawerTest">TESTING 1</v-btn><br><br> <v-btn @click="changeContent">TESTING 2</v-btn> <v-navigation-drawer v-model="drawerTest" height="100vh" width="360px" absolute hide-overlay right > <p> {{ content1 }} </p> </v-navigation-drawer> </div> </template> <script> export default { data() { return { drawerTest: false, content1: "This is the first test", content2: "HELLO" }; }, methods: { changeContent() { this.content1 = this.content2; }, } }; </script>
方案2:保留点击外部关闭,但按钮点击不关闭
如果需要保留点击页面其他区域关闭抽屉的功能,给第二个按钮添加@click.stop阻止事件冒泡,这样点击按钮时不会触发抽屉的关闭逻辑:
<template> <div> <v-btn @click="drawerTest = !drawerTest">TESTING 1</v-btn><br><br> <!-- 添加.stop修饰符阻止事件冒泡 --> <v-btn @click.stop="changeContent">TESTING 2</v-btn> <v-navigation-drawer v-model="drawerTest" height="100vh" width="360px" absolute temporary hide-overlay right > <p> {{ content1 }} </p> </v-navigation-drawer> </div> </template> <script> export default { data() { return { drawerTest: false, content1: "This is the first test", content2: "HELLO" }; }, methods: { changeContent() { this.content1 = this.content2; }, } }; </script>
注意:Vue模板中不需要用this.访问data变量,直接写{{ content1 }}即可,之前的{{this.content1}}属于冗余写法。
内容的提问来源于stack exchange,提问作者Quentin
相关产品推荐
相关产品推荐

