Hide a component in Vue.js

人盡茶涼 提交于 2019-12-22 09:38:50

问题


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


回答1:


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>



回答2:


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>


来源:https://stackoverflow.com/questions/44700257/hide-a-component-in-vue-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!