Giter Club home page Giter Club logo

vue-page-title's Introduction

Vue Page Title

Vue.js html/page title manager

Maintainability Test Coverage Scrutinizer Code Quality Build Status

Known Vulnerabilities Known Vulnerabilities Tests

Example App Doctype

Install npm version

yarn add vue-page-title # npm i vue-page-title

Setup

import { createApp } from 'vue';
import { pageTitle } from 'vue-page-title';

const app = createApp(Root);

app.use(
  pageTitle({
    suffix: '- Vue Page Title',
    mixin: true,
  })
);

Examples

Compatibility

Vue Version
v2 v1.*
v3 v2.*

Migration from v1

All resources from v1 works on v2.

Now mixin is optional and must be defined as true to be automatically registered in the app.

Options

Name Type Description
suffix String suffix for the value of the page title tag
prefix String prefix for the value of the page title tag
separator String a string that comes between the prefix and the title / the title and the suffix, defaults to a space
mixin Boolean if true, enable plugin mixin in the components
router VueRouter instance if present, allows you to set the title via the route.
setTitleMethod Function custom method of setting title

Usage

Composition API

<script>
import { createApp, h, ref, computed, onBeforeUnmount } from 'vue';
import { useTitle } from 'vue-page-title';

const CAPTAINS = [
  'Monkey D. Luffy',
  'Trafalgar D. Water Law',
  'Eustass Kid',
  'Shanks',
  'Edward Newgate',
  'Charlotte Linlin',
  'Capone Bege',
  'Gol D. Roger',
];

const getCapitain = () => CAPTAINS[Math.floor(Math.random() * CAPTAINS.length)];

export default defineComponent({
  setup() {
    const current = ref('Capitains');
    const { title } = useTitle(current);

    const refresh = () => {
      current.value = getCapitain();
    };

    const interval = setInterval(refresh, 5000);

    onBeforeUnmount(() => {
      clearInterval(interval);
    });

    return {
      title,
    };
  },
});
</script>

<template>
  <h1>{{ title }}</h1>
</template>
const { title } = useTitle('initial title`)

React from ref state

const name = ref('initial name');
const { title } = useTitle(name);

Use like a watch source argument

const product = ref({ name: 'One Piece 1017' });
const { title } = useTitle(() => product.name);

Pass a computed as argument

const product = ref({ name: 'One Piece 1017' });
const name = computed(() => product.name);
const { title } = useTitle(name);

Use setTitle to dynamically change the title

const product = ref({ name: 'One Piece 1017' });
const { setTitle } = useTitle();

watchEffect(() => {
  setTitle(product.name);
});

Mixin

With the mixin option enabled, just set the title option inside the component.
Within the component it is still possible to update the $title state using $setPageTitle function, it is also available to be used within the component template.

The option mixin must be true.

<script>
const CREW = [
  'Monkey D. Luffy',
  'Roronoa Zoro',
  'Nami',
  'Usopp',
  'Sanji',
  'Tony Tony Chopper',
  'Nico Robin',
  'Franky',
  'Brook',
  'Jinbe',
  'Nefertari Vivi',
];

export default {
  title: 'Mugiwara no Ichimi',
  mounted() {
    this.$interval = setInterval(() => {
      this.$setPageTitle(CREW[Math.floor(Math.random() * CREW.length)]);
    }, 2000);
  },
  beforeDestroy() {
    clearInterval(this.$interval);
  },
};
</script>

<template>
  <h1>{{ $title }}</h1>
</template>

Function title

You are able to turn the title changes acative, like a computed.

<script>
const EMPERORS = ['Shanks', 'Marshall D. Teach', 'Monkey D. Luffy', 'Buggy'];

export default {
  title() {
    return `🏴‍☠️ ${this.emperor}`;
  },
  data() {
    return {
      emperor: 'Four Emperors',
    };
  },
  mounted() {
    this.$interval = setInterval(() => {
      this.emperor = EMPERORS[Math.floor(Math.random() * EMPERORS.length)];
    }, 2000);
  },
  beforeDestroy() {
    clearInterval(this.$interval);
  },
};
</script>

<template>
  <h1>{{ $title }}</h1>
</template>

This is particularly useful for internationalization.
This is an example using vue-i18n@9.

export default {
  title: ({ $t }) => $t('pages.clients.title'),
};

Vue Router integration

Setup

import { createApp } from 'vue';
import { pageTitle } from 'vue-page-title';
import router from 'path/to/application/router';

const app = createApp(Root);

app.use(pageTitle({ router }));

path/to/application/router

import { createRouter, createWebHashHistory } from 'vue-router';
import FooComponent from 'path/to/foo-component';
import HomeComponent from 'path/to/home-component';

const routes = [
  {
    path: '/',
    component: HomeComponent,
    meta: {
      title: 'Home Page', // Title must be a string.
    },
  },
  {
    path: '/foo',
    component: FooComponent,
    meta: {
      title: 'Foo Page',
    },
  },
];

export default createRouter({
  history: createWebHashHistory(),
  routes,
});

Watching routes

export default {
  title() {
    return `My title is: ${this.$route.query.foo}`;
  },
};

vue-page-title's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

vue-page-title's Issues

Vue 3 support

Is there an estimate when this page will support vue 3?

Convite para fazer parte da Angola Open-source Community Mentorship

Olá, equipe vue-page-title

Espero que estejam bem. Sou Antonio Pedro da Angola Open-source Community, uma comunidade de desenvolvedores dedicados a promover o desenvolvimento open-source em Angola.

Estamos atualmente organizando um Programa de Mentoria em Desenvolvimento Open-source em Angola, visando capacitar os nossos desenvolvedores locais e estimular a colaboração com projetos de código aberto de renome internacional.

Gostaríamos de convidar ovue-page-title para participar como uma organização mentora no nosso programa. Acreditamos que a participação do vue-page-title como mentor pode ser extremamente valiosa para nossos desenvolvedores, permitindo que eles contribuam ativamente para um projeto relevante e aprendam com as melhores práticas de uma organização experiente.

O nosso programa terá duração de um mês e contará com diferentes etapas, incluindo pré-mentoria(onde nós a organização, iremos conduzir um workshop introdutório sobre open-source), mentoria, onde os desenvolvedores terão a oportunidade de trabalhar em qualquer issue aberta neste projeto, receber feedback de especialistas e desenvolver as suas habilidades em desenvolvimento de software.

Seria uma honra contar com o vue-page-title como um mentor no nosso programa. Acreditamos que essa colaboração pode trazer benefícios mútuos, fortalecendo a comunidade open-source em Angola e promovendo a inovação tecnológica em ambos os lados.

Se estiverem interessados em participar ou tiverem-se alguma dúvida, por favor, deixem-nos saber. Estamos ansiosos para uma possível parceria com ovue-page-title.

Agradecemos a sua atenção e consideração.

Atenciosamente,
Antonio Pedro
Angola Open-source Community

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper App’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.

Improve title reactivity

Cenario

My app needs to change the title when the url`s query params are updated. I create a computed property to react to the url query params and the page title is static and does not react to computed changes.

Actual behavior

The page title is static and does not react to computed changes.

Suggestion

My suggestion is for the title reacts without need to watching the $route.query property.

<script>
export default {
  title: ctx => ctx.reactiveTitle,
  computed: {
    reactiveTitle() {
      return `My title is: ${this.$route.query.foo}`
    },
  },
}
</script>

Workaround

I solve this watching at the $route.query property and when modified it calls a method that updates the title.

<script>
export default {
  title: ctx => ctx.getPageTitle(),
  computed: {
    reactiveTitle() {
      return `My title is: ${this.$route.query.foo}`
    },
  },
  watch: {
    '$route.query'() {
      this.$title = this.getPageTitle();
    },
  },
  methods: {
    getPageTitle() {
       return this.reactiveTitle
    },
  },
}
</script>

Is this a valid and possible improvement?

Add $titlePrefix & $titleSuffix

Adding prototypes for $titlePrefix & $titleSuffix or variant allowing you to modify the options and re calling SetTitle within index.js would be helpful for tasks such as showing notification/new message counts dynamically, independent of what the current title is set to by another component.

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper App’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.

Add separator option

Do you think it would be a good idea to have a separator option?

It would work as follows:

pageTitle({
  suffix: 'The Best Page On The Internet',
  separator: ' - ',
})

The page title will be:

  • 'The Best Page On The Internet' for useTitle(ref(''))
  • 'Photos - The Best Page On The Internet' for useTitle(ref('Photos'))

So it doesn't add the separator if the title is blank. I see this as useful for homepages or for pages that get their title asynchronously.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.