Vue-router: dynamic HTML with links

Created on 7 Jul 2015  ·  6Comments  ·  Source: vuejs/vue-router

Hey

I get via an API, HTML containing links :

{
  "html":"<a href='/fr/hello-world'>Hello world</a>"
}

To avoid the page reloads on click, I need to apply the v-link directive right ?
So I create another directive which compiles my DOM element.

var a = this.el.querySelectorAll('a');
_.forEach(a, function(el) {
  el.setAttribute('v-link', el.getAttribute('href'));
  _this.vm.$compile(el);
});

It works like I want, but maybe there is a more "official" way to do this ?

In any case, bravo for the hard work behind Vue.js :+1:

Most helpful comment

This should work, but $compile() is pretty low-level and you need to store the returned unlink function and call them later for proper cleanup. The probably easier way is to intercept click events on a containing element, call event.preventDefault(), then call router.go() yourself.

Maybe I should add an option for global link hijacks.

All 6 comments

This should work, but $compile() is pretty low-level and you need to store the returned unlink function and call them later for proper cleanup. The probably easier way is to intercept click events on a containing element, call event.preventDefault(), then call router.go() yourself.

Maybe I should add an option for global link hijacks.

@yyx990803 did you add an option for global link hijacking? If so how can it be used.

I'm currently using the following workaround in the top level component (this might be a naive solution):

mounted() {
    window.addEventListener('click', event => {
        let target = event.target
        while (target != null && target.tagName != 'A') {
            target = target.parentNode;
        }
        if (target && target.href && this.isSameDomain(target.href)) {
            event.preventDefault();
            this.$router.push(this.$options.filters.relativize(target.href));
        }
    });
},

isSameDomain speaks for itself and the relativize filter returns the full path of the url.

You probably won't get a reply from Evan asking a question in a two year old, closed issue hardly related to the original topic.

I suggest to use our forum instead to ask the community: forum.vuejs.org

@LinusBorg the reason why I'm using that code snippet is exactly what this issue is about; dynamic html containing links. Which I would like being handeled by Vue Router instead of doing a page reload.

But sure, I'll try the forum.

@matsrietdijk Do you know if the global link hijacking is implemented :)? I don't see this in the docs, so I guess your solution is still the best one?

No it's not. Otherwise it would be in the docs.

Was this page helpful?
0 / 5 - 0 ratings