vue页面组件化,导入、使用和只显示页面组件的一部分

前言

  • 本文代码为vue3,把A页面作为父页面,B页面作为子组件在A页面里展示。

  • A页面最终效果,展示了部分B页面内容
    在这里插入图片描述 点击A页面按钮,展示了全部B页面内容在这里插入图片描述

  • B页面
    在这里插入图片描述

一、导入

  • 在A页面里写如下代码,因为想在A页面导入B页面作为组件。
import indexB from '@/views/demo/pageB/indexB.vue';

二、使用(全部显示)

  • 在A页面里写如下代码,导入完成后,使用此代码可展示B页面内容。
 <indexB></indexB>

三、显示页面组件的部分(部分显示)

  • 假设希望只展示B页面的 B内容1,不展示页面BB内容2
  • 在B页面里写如下代码,B组件里isShow的值默认为true,代表默认展示页面BB内容2。当isShow为false时不展示。
    <h1 class="title"  v-show="isShow">页面B</h1>
    <div class="content">B内容1</div>
    <div class="content"  v-show="isShow">B内容2</div>
    <script setup lang="ts">
	const props = defineProps({
	  //是否父子联动,true默认显示
	  isShow: {
	    type: Boolean,
	    default: true
	  }
	});
	</script>
  • 在A页面里写如下代码,展示B组件,并且给B组件传值,让B组件的isShow值为false,让B页面不展示页面BB内容2,得到只展示B页面的 B内容1的结果。
    <indexB :isShow="false"></indexB>
  • 父组件(A页面)通过props向子组件(B页面)传递数据。props是单向的,即父组件可以传递数据给子组件,但子组件不能修改父组件传递的数据。

完整代码

  • A页面
<template>
  <div class="container">
    <h1 class="title">页面A</h1>
    <button @click="handleClick" class="btn">点击按钮</button>
    <div class="content">A内容1</div>
    <div class="content">A内容2</div>
    <indexB :isShow="false"></indexB>
    <el-dialog title="出现页面"
      v-model="dialogVisible.visible"
      :style="{ height: '700px' }" @close="handleClose">
    <indexB></indexB>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import indexB from '@/views/demo/pageB/indexB.vue';
const dialogVisible = reactive<DialogOption>({
  visible: false,
});
const handleClick = () => {
  dialogVisible.visible = true
  console.log('按钮被点击了');
};
const handleClose = () => {
  console.log('关闭页面');
};
</script>
  • B页面
<template>
  <div class="container">
    <h1 class="title"  v-show="isShow">页面B</h1>
    <div class="content">B内容1</div>
    <div class="content"  v-show="isShow">B内容2</div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
const props = defineProps({
  //是否父子联动,true默认显示
  isShow: {
    type: Boolean,
    default: true
  }
});
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值