路线更改时如何更新我的Vue组件?

时间:2019-07-04 21:10:39

标签: vue.js

我有一个组件:

<template>
  <ul class="nav nav-pills nav-fill fixed-bottom">
    <li class="nav-item">
      <router-link to="/app">
        <a class="nav-link active" href="/app">
          <i class="material-icons md-48">view_list</i>
        </a>
      </router-link>
    </li>
...
  </ul>
</template>

<script>
export default {
  name: "Navigation"
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.nav {
  background: white;
  border-top: 0.1px solid silver;
}

.nav-pills .nav-link {
  border-radius: 0;
}
</style>

组件如何知道路径何时更改以及当前路线是什么?

2 个答案:

答案 0 :(得分:1)

您可以通过this.$route访问当前路线。实际路径位于this.$route.path。此属性是反应性的,因此您可以以通常使用反应性的任何方式使用它。如果希望Vue在路线更改时强制创建新组件,则可以使用:key="$route.path"在路径更改上创建新组件。先前的组件将被销毁并调用其适当的生命周期挂钩,而新组件将调用其createdmounted挂钩。

答案 1 :(得分:1)

我使用vuex做了一个简单的示例,但是它解释了@ Sumurai8所说的内容。我唯一没有添加的是:key来销毁该组件。

您可以尝试here

const Navigation = {
  template: '#navigation',
  data: function() {
    return {
      oldRoute: null
    }
  },
  computed: {
    myRoute: function() {
      return this.$route.path
    }
  },
  watch: {
    '$route.path': function(newVal, oldVal) {
      this.oldRoute = oldVal
    }
  }
};

const Home = {
  template: '#home',
}

const Component1 = {
  template: '#component1'
};

const Component2 = {
  template: '#component2'
};


const routes = [{
    path: '',
    component: Home
  },
  {
    path: '/1',
    component: Component1
  },
  {
    path: '/2',
    component: Component2
  }
]

const router = new VueRouter({
  routes
});

Vue.component('Navigation', Navigation)

new Vue({
  router
}).$mount('#app');
#app {
  max-width: 850px;
  margin: 20px auto;
  text-align: center;
}

ul>li {
  display: inline-block;
  margin-right: 20px;
}

.wrapper {
  display: flex;
  justify-content: space-between;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.0.7/vue-router.min.js"></script>



<script type="text/x-template" id="home">
  <div>
    <h2>Home</h2>
    <ul>
      <li>
        <router-link to="/1">Component 1</router-link>
      </li>
      <li>
        <router-link to="/2">Component 2</router-link>
      </li>
    </ul>
  </div>
</script>

<script type="text/x-template" id="component1">
  <div>
    <h2>Component 1</h2>
    <ul>
      <router-link to="/">Home</router-link>
    </ul>
  </div>
</script>

<script type="text/x-template" id="component2">
  <div>
    <h2>Component 2</h2>
    <ul>
      <li>
        <router-link to="/">Home</router-link>
      </li>
    </ul>
  </div>
</script>

<script type="text/x-template" id="navigation">
  <div>
    <div> <strong>my route is:</strong> {{myRoute}}</div>
    <div> <strong>old route:</strong> {{oldRoute}}</div>
  </div>
</script>

<div id="app">
  <div class="wrapper">
    <h1>Basic Vue-Router</h1>
    <Navigation />
  </div>
  <router-view></router-view>

</div>