簡體   English   中英

在 Vue 上,如何在另一個組件中使用一個組件的功能?

[英]on Vue, how to use a function from a component in another component?

我有這個組件,功能“注銷”如下:

// @/component/Painel.vue
<template></template>
<script>
export default {
  name: 'panel',
  methods: {
    logout: function () {
      this.$session.destroy()
      this.$router.push('/')
    }
  }
}
</script>

我需要在 Navbar.vue 中使用 Painel.vue 中定義的函數“注銷”,如下所示:

// @/component/Navbar.vue
<template>
<div class="navbar">
    <a @click="logout" class="nav-link m-2 my-2 my-md-0" >Sair</a>
</div>
</template>

<script>
export default {
    name: 'navbar'
}
</script>

我試圖導入組件並使用這樣的功能,但沒有奏效

import Painel from '@/components/authentication/Painel.vue'
...
this.logout()

我怎樣才能做到這一點?

有兩種方法可以做到這一點。 您應該使用哪個取決於需要如何調用該函數。

選項 1. (插件)如果任一組件需要以編程方式調用logout功能,而不是僅包含一個用於嚴格注銷目的的按鈕。 例如,如果一個組件包含像“提交和注銷”這樣的按鈕,那么logout是附加功能,需要以編程方式調用。

在這種情況下,您應該將logout重構為一個單獨的插件,用作在 Vue 中提供全局范圍的功能或其他屬性的一種方式。

一個例子:

const LogoutPlugin {
    install(Vue, options) {
        Vue.prototype.$logout = function() {
            // logout logic
        }
    }
}

Vue.use(LogoutPlugin);

new Vue({
   // ... options
})

然后可以使用this.$logout() logout注銷。

選項 2. (組合)如果兩個組件都只需要有注銷按鈕,那么您可以通過創建一個LogoutButton組件來完成此操作,並將其放置在兩個組件內。

例子:

<template>
    <button @click="logout">Log Out</button>
</template

<script>
export default {
    name: "LogoutButton",
    methods: {
        logout() {
            // logout logic
        },
    }
}
</script>

然后在需要它的任何組件中放置一個LogoutButton 像這樣:

<template>
    <div class="navbar">
        <LogoutButton/>
    </div>
</template>

<script>
import LogoutButton from './LogoutButton.vue';

export default {
    name: "NavBar",
    components: {
        LogoutButton
    }
}
</script>

您可以為組件之間的通信創建 EventBus。

<script>
import Vue from 'vue'

Vue.prorotype.$bus = new Vue()

//app init
</script>

在您的根組件中定義方法logout后,例如 App.vue。 並在mounted中添加事件監聽器

<script>
export default {
    mounted () {
        this.$bus.$on('logout', () => this.logout())
    },
    methods: {
        logout () {
            this.$session.destroy()
            this.$router.push('/')
        }
    }
}
</script>

然后在任何組件中,您都可以使用this.$bus.$emit('logout')發出logout事件

鏈接: 創建事件總線

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM