2015-09-05 28 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; 
相关问题