AmazingDreams / vue-matomo

Vue plugin for Matomo Analytics
MIT License
272 stars 60 forks source link

How to set page title after loading async data? #137

Closed arildm closed 4 months ago

arildm commented 1 year ago

I'm setting up vue-matomo with vue-router, and it tracks page views as expected. Now I want to set the correct page titles.

In some of my view components, I am loading async data and then setting document.title (using VueUse useTitle if that's relevant). So, I am pushing the setDocumentTitle method a little while after the route is visited. In the Matomo backend, I don't see the title being tracked.

I guess I will need to push setDocumentTitle before the plugin tracks the page view. Can I control the order of these events somehow?

Here is a redacted fragment of my code, for reference:

<script setup>
// [...]

const work = ref();

getData().then((data) => (work.value = data));

const title = computed(() => work.value && work.value.title);

watchEffect(() => {
  if (title.value) {
    document.title = title.value;
    console.log("setDocumentTitle", title.value);
    window._paq.push(["setDocumentTitle", title.value]);
  }
});
</script>
jheuing commented 4 months ago

@arildm did you find a solution for this issue? Just stumbled upon it as well... Thanks loads for sharing your solution!

arildm commented 4 months ago

@jheuing It looks like this plugin is hardwired to track the page view in a router.afterEach hook (docs):

https://github.com/AmazingDreams/vue-matomo/blob/52f6a8dc3bc333b1218dd1b51295a10f544a28bf/src/index.js#L101-L103

Maybe you could set the title in another navigation guard, although I'm not sure if/how you can control the order of multiple guards. Yours would need to come in before this one.

In my case, the title isn't available until after an async fetch. You can fetch data as part of the navigation step, as described here, but I haven't looked into that. I ended up skipping the router option to this plugin, and instead I'm calling window._paq.push() directly, after fetching data. See my matomo.composable.ts

And I guess, with that, I have answered my own question in this issue, so I'm closing it.

jheuing commented 4 months ago

@arildm Haha, thanks :)

I came to the conclusion that for analytics the page title is equivalent good enough as the URL actually is, considering the URL is speaking. So I could also live with just the URLs, even though the title would be nicer. If there would be an option (which I didn't find) to disable the action by default, I could just track the page view manually on load. All the efforts might be obsolete considering page urls might be good enough for now at least.

Thanks loads for coming back to this after ages :-)