2017-03-06 98 views
0

我想從其他JS文件中調用我的通知函數,但它總是返回undefined來自其他js文件的Javascript(Vue)調用函數返回undefined

notification.js

function notification(message, level = 'success') { 
    Lobibox.notify(level, { 
     delayIndicator: false, 
     msg: message 

    }); 
} 

addToCart.vue

<template> 
    <div> 
    <button class="button dark small" @click="addToCart(menu, price)"> 
     <i class="fa fa-cutlery fa-lg m-right-5"></i> 
     Pilih Menu 
    </button> 
    </div> 
</template> 

<script> 
    export default{ 
     props: ['menu', 'price'], 

     methods:{ 
      addToCart(menu, price){ 
       const currentPoint = $('#current_point').val(); 

       if(price > currentPoint){ 
        return notification('Point is not enough', 'error') 
       } 


      } 
     } 
    } 
</script> 

app.js

Vue.component('addtocart', require('./components/AddToCart.vue')); 
new Vue({ 
    el: '#app' 
}); 

HTML:

<script src="{{ asset('js/notification.js') }}"></script> 
<script src="{{ asset('js/app.js') }}"></script> 

每次price > currentPoint得到稱它總是返回我Uncaught ReferenceError: notification is not defined

我使用LaravelMix進行編譯。

任何解決方案?

+0

您的通知方法沒有任何return語句。所以它返回undefined –

回答

0

notification.js

function notification(message, level = 'success') { 
    Lobibox.notify(level, { 
     delayIndicator: false, 
     msg: message 

    }); 
} 

window.notification = notification; 

解決它。我需要添加window.notification = notification,所以我可以隨處調用它。

0

看來你只需要做你的HTML如下:

<script src="js/notification.js"></script> 
<script src="js/app.js"></script> 
+0

我使用Laravel。我的代碼將完全像你的一樣渲染 – ssuhat

0

最好避免把東西放在窗口中。

看起來你正在使用帶有webpack的Vue。如果你不是,那麼這是行不通的。如果你是這樣,你最好使用ES6模塊來確保你可以訪問你需要的東西。

在您notification.js文件:

export default user 

然後您可以致電

import notification from 'notification'