根据路线更改img src

时间:2019-02-23 11:08:51

标签: vue.js vue-router

我有一个标头组件,其左侧带有徽标图像,就像这样-

<router-link to="/">
    <img id="top-logo" src="@/assets/images/logo/logo-ft-on-tp.svg">
</router-link>

现在,我希望此徽标仅出现在主页上,并在所有其他页面上加载不同的图像。如何在VueJS中实现这一目标?

1 个答案:

答案 0 :(得分:0)

您可以使用this.$router.path来破坏当前路径:

const Home = {
  template: '<div>Home</div>'
}
const Foo = {
  template: '<div>Foo</div>'
}

const router = new VueRouter({
  mode: 'history',
  routes: [{
      path: '/',
      component: Home
    },
    {
      path: '/foo',
      component: Foo
    }
  ]
})

new Vue({
  router,
  el: '#app',
  computed: {
    checkIfHome() {
      return (this.$route.path === '/') ? true : false
    }
  }
})
<script src="https://npmcdn.com/vue/dist/vue.js"></script>
<script src="https://npmcdn.com/vue-router/dist/vue-router.js"></script>

<div id="app">
  <div v-if="checkIfHome">home image</div>
  <div v-else>other image</div>

  <router-link to="/">/home</router-link>
  <router-link to="/foo">/foo</router-link>

  <router-view></router-view>
</div>

Check the fiddle for a working example