简体   繁体   中英

Polymer - Change page title with iron-pages

Lets say I have the demo implementation of iron-pages (from its Github page ):

<iron-pages selected="0">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
</iron-pages>

<script>
  document.addEventListener('click', function(e) {
    var pages = document.querySelector('iron-pages');
    pages.selectNext();
  });
</script>

Now, I want to add a suffix to the page title to reflect the selected page. So for <div>One</div> I would like to append - selected One and so on.

What I've got so far is to make the change in routing.html when the route has been selected but it seems a bit weird to make the change here. Are there any other ways of doing this?

You should take a look at my Polymer component <page-title> here: https://github.com/zacharytamas/page-title/ . You can install it with Bower, too:

bower install page-title --save

Likely you'd want some kind of function that maps the selected index from <iron-pages> to text you want to show as the title. In your example you could just the innerText of the selected element, but in practice your <iron-pages> elements would actually have content in them.

This will depend on your setup but you could use my component to easily bind them, something like this:

<dom-module id="my-app">
  <template>

    <page-title base-title="My Website" 
      title="[[selectedPage.title]]"></page-title>

    <iron-pages selected-item="{{selectedPage}}">
      <div title="First Page">One</div>
      <div title="Second Page">Two</div>
      <div title="Third Page">Three</div>
    </iron-pages>

  </template>
  <script>
    Polymer({
      is: 'my-app'
    });
  </script>
</dom-module>

Here I've just done some fanciness to bind the title of the page to the title attribute of the currently selected element from the <iron-pages> . It works pretty well! You may have to adopt to your situation but this should get you going.

The value of your title element can be a computed property based on the value of {{selected}}, ie:

<myTitle text={{title}} currentSelection={{selected}}></myTitle>

//declarative portion of element

<dom-module id="myTitle">
<template>
    <div>{{title}}</div>
</template>
</dom-module>

//imperative portion

Polymer({

is: 'myTitle',

properties: {
    title: {
        type: String,
        computed: 'generateTitle'
    },

    currentSelection: {
        type: Number
    }
},

'generateTitle': function(){
    return '- selected' + this.currentSelection;
}

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM