Hide a component in Vue.js

2019-07-01 15:19发布

Is there a way with which I can control the rendering of a shared component in another component? I have a component which is a bottom bar which needs to be disabled/ not rendered in a few concrete components.

I am rendering the bottom bar in a template which is being used by all the components.

EDIT: I am using webpack

2条回答
一夜七次
2楼-- · 2019-07-01 15:38

As Roy said, you could have a property that conditions the rendering of the component, as such (assuming you're using vue-loader):

<template>
  <div v-if="shouldRender">
    <!-- ... -->
  </div>
</template>

<script>
export default {
  props: ['shouldRender']
}
</script>

then, in your parent component:

<template>
  <div>
    <!-- ... -->
    <BottomBar :should-render="showBottomBar" />
  </div>
</template>

<script>
export default {
  data () {
    return {
       showBottomBar: true
    }
  },
  methods: {
    toggleBottomBar () {
      this.showBottomBar = !this.showBottomBar
    }
  }
}
</script>
查看更多
Rolldiameter
3楼-- · 2019-07-01 16:04

Use vue-router

const Header = {template: '<div>component header</div>'}
const Main = {template: '<div>component main</div>'}
const Footer = {template: '<div>component footer</div>'}

const router = new VueRouter({
  routes: [
    { 
      path: '/link1', 
      components: {
        header: Header,
        main: Main,
        footer: Footer
      }
    },
    { 
      path: '/link2', 
      components: {
        header: Header,
        main: Main
      }
    }
  ]
})

const app = new Vue({ router }).$mount('#app')
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/2.6.0/vue-router.min.js"></script>

<div id="app">
  <router-link to="/link1">/link1</router-link>
  <router-link to="/link2">/link2</router-link>

  <router-view class="" name="header"></router-view>
  <router-view class="" name="main"></router-view>
  <router-view class="" name="footer"></router-view>
</div>

查看更多
登录 后发表回答