Change Vue view by object rather than url router

Viewed 93

Writing a chrome extension with Vue.js and I need to change the views based on user action.

Typically, I would use the Vue router to auto-magically abstract all this logic away... however the router is bound to the URL.

Is it possible to change this behaviour in any way?

i.e, the <router-view/> is in App.vue as normal, but as the user clicks through the extension the router is not watching the URL in the browser address bar but instead say some other object?

1 Answers

Dynamic Components

Vue router is specifically for the url bar. You can use dynamic components when you want to switch a view component based on some other data. It uses a <component> tag with an is attribute:

<component :is="currentTabComponent"></component>

From the docs:

In the example above, currentTabComponent can contain either:

  • the name of a registered component, or
  • a component’s options object

Here's a demo where the variable currentTabComponent contains the name of the component:

new Vue({
  el: "#app",
  components: {
    Home: { template: `<div class="component"><h1>Home</h1> The home component</div>` },
    About: { template: `<div class="component"><h1>About</h1> An about component</div>` },
  },
  data() {
    return {
      currentTabComponent: 'Home'
    }
  },
  methods: {
    toggle() {
      this.currentTabComponent = this.currentTabComponent === 'Home' ? 'About' : 'Home';
    }
  }
});
.component {
  border: 3px solid #cccccc;
  margin: 10px;
  padding: 12px;
}
<div id="app">
  <component :is="currentTabComponent"></component>
  <button @click="toggle">Toggle</button>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

Related