2015-09-05 30 views
1

我在設置我的Vue組件時遇到問題,以便在用戶處於移動狀態時以不同方式處理其方法。例如導航下拉菜單,如果用戶點擊一個鏈接,我想阻止他們去那個位置,而是下拉下拉菜單。而在桌面上,我希望他們在點擊它時只能點擊鼠標懸停。我需要爲我的項目的許多其他方面。在Vue中根據手機的不同而採用不同的處理方法

我有一個主要的Vue實例:

var Main = new Vue({ 
    el: 'body', 

    data: { 
     mobile: true 
    }, 

    ready: function() { 
     if(document.clientWidth >= 992) 
     { 
      this.mobile = false; 
     } 
    } 
}); 

export default Main; 

那麼對於我的成分,我在做這樣的事情:

import Main from './../Main'; 

var NavLink = Vue.component('navlink', { 
    template: '#nav-link-template', 

    replace: true, 

    data: function() { 
     return { 
     } 
    }, 

    props: ['text', 'url'], 

    ready: function() { 
    }, 

    methods: { 
     handleClick: function(e) { 
      e.preventDefault(); 
      console.log(Main.mobile); 

      if(Main.mobile) 
      { 
       if(this.$children.length) 
       { 
        // Has dropdown 
        this.$children[0].dropDown(); 
       } 
       else 
       { 
        // No dropdown so redirect user 
        window.location = this.url; 
       } 
      } 
      else 
      { 
       // Not mobile so let user go 
       window.location = this.url; 
      } 
     } 
    } 
}); 

不僅Main.mobile返回默認值事情沒有解決什麼因爲他們的準備好的方法似乎在主準備好的方法之前運行......但這也感覺就像錯誤的設置。

感謝您的任何見解。

+0

使用混入https://vuejs.org/v2/guide/mixins.html –

回答

0

首先,根據你的代碼,你不需要主commonjs模塊是一個vuejs實例。讓它作爲一個簡單的JS對象

Main = { 
    mobule: document.clientWidth >= 992 
} 

export default Main; 

或者你可能要處理客戶端的窗口大小動態

var Main = new Vue({ 
    created: function() { 
     // dunno why v-on="resize: func" not working 
     global.window.addEventListener('resize', function() { 
      //calc width and heigh somehow 
      self.$broadcast('resize', width, heigh); 
     }); 
    } 
}); 

export default Main; 
相關問題