通过对象而不是 url 路由器更改 Vue 视图

Change Vue view by object rather than url router

使用 Vue.js 编写 chrome 扩展,我需要根据用户操作更改视图。

通常,我会使用 Vue 路由器自动神奇地抽象出所有这些逻辑......但是路由器绑定到 URL。

是否可以通过任何方式改变这种行为?

<router-view/> 正常在 App.vue 中,但是当用户点击扩展时,路由器不会在浏览器地址栏中查看 URL 而是说其他一些对象?

动态组件

Vue router 是专门针对url吧。您可以使用 dynamic components when you want to switch a view component based on some other data. It uses a <component> tag with an is 属性:

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

来自文档:

In the example above, currentTabComponent can contain either:

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

这是一个演示,其中变量 currentTabComponent 包含组件的名称:

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>