Vue引用其他组件,但组件某些部分不需要时的简单处理

项目开发时,我们会把多个地方重复使用的模块抽象成组件,提供给大家一起使用,但是使用组件的时候偶尔会遇见一些问题,比如说组件里只有某些东西自己并不需要,这个时候我们可以对组件进行简单的修改,而不影响其他人的使用。

这里有一个方法,举个例子简单说明一下。

我们在页面上引入一个其他组件,然后给组件传入一个状态值。

页面

<template>
  <div>
    <show-my-test :state="true"></show-my-test>
  </div>
</template>

<script>
  import showMyTest from '~/components/showMyTest.vue';
  export default {
    name: 'index',
    components: {
      showMyTest: showMyTest
    }
  };
</script>

<style scoped>

</style>

组件通过props获取Boolean类型的值,如果没有获取到值则会默认为false,我们可以通过这个来解决一些问题。

组件

<template>
  <div>
     <div>
       <p>今天是周一!</p>
     </div>
     <div v-if=“!state”>
       <p>今天天气不错</p>
     </div>
  </div>
</template>

<script>
  export default {
    name: 'index',
    props: {
      state: {
        type: Array
     }
  };
</script>

<style scoped>

</style>

这样的话,在使用上面这个组件的时候,如果没有给组件传state的值,则今天天气不错那里正常显示,不影响使用,如果给组件传了一个true的值,则这一块则不会显示。

通过这样的方法可以解决挺多组件复用时候产生的问题,这里只是一个简单的例子,实际问题应该根据需求来处理。

恩,就酱~

猜你喜欢

转载自www.cnblogs.com/jin-zhe/p/9268602.html