3 回答

TA貢獻1821條經驗 獲得超5個贊
您可以在 上發出一個事件$root
,該事件可用于切換側邊欄。第二個參數是id
你想打開的側邊欄。 this.$root.$emit('bv::toggle::collapse', 'my-sidebar-id')
<b-collapse>
并<b-sidebar>
監聽相同的事件,這就是它collapse
在事件中說的原因。
new Vue({
el: '#app',
methods: {
openSidebar() {
this.$root.$emit('bv::toggle::collapse', 'my-sidebar')
}
}
})
<link href="https://unpkg.com/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://unpkg.com/[email protected]/dist/bootstrap-vue.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script>
<script src="https://unpkg.com/[email protected]/dist/bootstrap-vue.js"></script>
<div id="app">
<b-sidebar id="my-sidebar" right>
My sidebar
</b-sidebar>
<b-btn @click="openSidebar">
Open sidebar
</b-btn>
</div>
或者,您可以將布爾屬性綁定到v-model
側邊欄上,并將布爾值設置為true
您想要打開側邊欄的時間。
new Vue({
el: '#app',
data() {
return {
isSidebarOpen: false
}
},
methods: {
openSidebar() {
this.isSidebarOpen = true
}
}
})
<link href="https://unpkg.com/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://unpkg.com/[email protected]/dist/bootstrap-vue.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script>
<script src="https://unpkg.com/[email protected]/dist/bootstrap-vue.js"></script>
<div id="app">
<b-sidebar v-model="isSidebarOpen" right>
My sidebar
</b-sidebar>
<b-btn @click="openSidebar">
Open sidebar
</b-btn>
</div>

TA貢獻1877條經驗 獲得超1個贊
此外,您還可以使用側邊欄內置的公共方法之一show,hide或toggle。您所需要的只是添加對側邊欄的引用
<b-sidebar ref="mySidebar" id="do-it-form">
...
</b-sidebar>
然后在您需要的任何方法中/何時需要,您可以簡單地調用它們中的任何一個
this.$refs.mysidebar.show();
this.$refs.mysidebar.hide();
this.$refs.mysidebar.toggle();

TA貢獻1785條經驗 獲得超8個贊
visible您也可以只為組件上的 prop分配一個布爾值b-sidebar,并根據需要切換布爾值。
<b-sidebar ref="mySidebar" id="do-it-form" :visible="showSidebar">
...
</b-sidebar>
并切換它:
data: {
showSidebar: false, //starts off invisible
},
methods: {
toggleSidebar(){
this.showSidebar = !this.showSidebar
}
}
乍一看,這種方法并不是最好的方法,因為你有其他組件來更新側邊欄的可見性。此用例適用于側邊欄可見性的所有更新都是通過使用中央布爾值從中央存儲進行的情況。
例如
const state = {
showSidebar: null
}
const mutations: {
toggleSidebar(state, payload){
if (payload) { //payload incase you want to force a value and not just toggle
state.showSidebar = payload;
} else {
state.showSidebar = !state.showSidebar;
}
}
}
在您的組件中:
computed: {
showSidebar(){
return this.$store.state.showSidebar
}, //starts off invisible
},
methods: {
toggleSidebar(){
this.$store.commit("toggleSidebar");
}
}
您更新的側邊欄組件將如下所示:
<b-sidebar ref="mySidebar" id="do-it-form" :visible="showSidebar" @change="updateSidebar">
...
</b-sidebar>
和方法:
methods: {
updateSidebar(value){
this.$store.commit("toggleSidebar", value);
}
}
添加回答
舉報