2017-12-18 110 views
0

我很難編寫一個全局方法來檢查NuxtJS中的驗證。我可以編寫的方法v-if在組件中顯示,如果它返回True。 我把這段代碼放在layout/default.vue中,但它不起作用。編寫一個全局方法來檢查NuxtJS中的驗證

/layout/defaut.vue

<script> 
import '~/assets/icons' 
export default { 
    head() { 
    return !this.mobileLayout ? {} : { 
     bodyAttrs: { 
     class: 'mobile' 
     } 
    } 
    }, 
    created() { 
    this.LoggedIn() 
    }, 
    methods: { 
    LoggedIn: function() { 
     return this.$store.state.authUser 
    } 
    } 
} 
</script> 

組件:

<template> 
    <div v-if="LoggedIn">Authenticated</div > 
</template> 

錯誤:

Property or method "LoggedIn" is not defined on the instance but referenced during render 

希望你小子幫我!

回答

0

由於authUser是vuex中的狀態屬性,而不是方法。您組件中的LoggedIn只是從狀態返回一個值,並不需要是一個方法。

您應該使用計算而不是方法。您也不需要從創建的方法調用LoggedIn,一旦它被計算出來,它就會自動計算。

<script> 
import '~/assets/icons' 
export default { 
    head() { 
    return !this.mobileLayout ? {} : { 
     bodyAttrs: { 
     class: 'mobile' 
     } 
    } 
    }, 
    computed: { 
    LoggedIn: function() { 
     return this.$store.state.authUser 
    } 
    } 
} 
</script> 

甚至更​​好,使用mapState從vuex這是記錄在這裏https://vuex.vuejs.org/en/state.html

<script> 
import Vuex from 'vuex' 
import '~/assets/icons' 
export default { 
    head() { 
    return !this.mobileLayout ? {} : { 
     bodyAttrs: { 
     class: 'mobile' 
     } 
    } 
    }, 
    computed: { 
    ...mapState({ 
     LoggedIn: 'authUser' 
    }) 
    } 
} 
</script> 

您的模板並不需要改變。

相關問題