首页 > 解决方案 > 路由更改时如何更新我的 Vue 组件?

问题描述

我有一个组件:

<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>

组件如何知道路径何时发生变化以及当前路由是什么?

标签: vue.js

解决方案


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

你可以在这里试试

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>


推荐阅读