How to implement routing in polymer 3 using app-route

前端 未结 1 592
一生所求
一生所求 2020-12-19 18:44

I was stuck with implementing routing in polymer 3. I followed the basic guide provided on app-route documentation. But on loading the web page., I don\'t

1条回答
  •  死守一世寂寞
    2020-12-19 18:58

    You need to have

    app-route: for implementation of routing

    Iron pages: Basically page switcher to load required component on demand

    In app-route.,

    /* observer: Its a simple observer (basically a watch which holds current value & old value) that triggers whenever data changed in page property. We read the observer and calls a function to grab its earlier */
    
    static get properties() {
      return {
      page:{
        type: String,
        reflectToAttribute: true,
        observer: '_pageChanged'
      }
      };
    }
    _pageChanged(currentPage, oldPage){
    	  console.log('CURRENT - ', currentPage);
    	  console.log('OLD - ', oldPage);
    	  switch(currentPage){
    		  case 'home':
    			import('./home-comp.js').then()
    			break;
    		case 'about':
    			import('./about-comp.js').then()
    			break;
    		case 'contact':
    			import('./contact-comp.js').then()
    			break;
    		default:
    			this.page = 'home';
    	  }
      }
    
    
    
    	

    But for first time loading., page property doe not hold any value and throws undefined.

    Hence we can use complex observer to observe such changes

    static get observers(){
    	return ['_routerChanged(routeData.page)'];
    }
    _routerChanged(page){
    	console.log('CHANGED PAGE - ', page);
    	this.page = page || 'home';
    }

    Changed route data does not load the components unless we have iron-pages. Its basically a component switcher/loader on demand. Wrap all component in main-app under

    
    
    
    
    
    
    		
    		
    		
    

    Here is the complete guide for routing implementation in polymer 3 using app-route. Hope this helps click here

    0 讨论(0)
提交回复
热议问题