Vue中的组件嵌套

本文档详细介绍了在Vue中实现组件嵌套和同级关系的过程,通过一个具体的例子展示了如何创建school1和school2组件,并在它们内部嵌套student和hello组件。在遇到组件同级显示时遇到的错误及解决方案,通过代码对比说明了问题的修正过程,帮助读者理解Vue组件间的组织和通信机制。
摘要由CSDN通过智能技术生成

今天完成的是一个组件嵌套功能,实现的是如下效果,其中school1 与school2是同级关系

在这里插入图片描述

我是这么想的:先用app去接管vm中的所有组件,app中有school1组件和school2组件,然后在school1中嵌套studentstudent组件中嵌套hello

在解决组件school1schoo2同级关系时,控制台报了如下错误,奇奇怪怪的错误让我school1school2不能同时出现

在这里插入图片描述

在经过理解转化之后,修改代码前后对比如下【后者为正确代码】

在这里插入图片描述

在这里插入图片描述

话不多说,直接上代码理解

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>组件的嵌套</title>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

</head>
<body>
  <div id="root">
    <app></app>
  </div>
  <script>
    // 定义hello组件
    const hello = Vue.extend({
      template:`
        <h2>{{message}}</h2>
      `,
      data(){
        return{
          message:'欢迎来到Vue开发学习'
        }
      }

    })

    // 定义student子组件
    const student = Vue.extend({
      name:'student',
      template:`
      <div>
      <h2>学生姓名名称:{{name}}</h2>
      <h2>学生年龄:{{age}}</h2>
      <hello></hello>
</div>
      `,
      data(){
        return{
          name:'张小北',
          age:18
        }
      },
      // 注册组件(局部)
      components:{
        hello
      }
    })
    // 定义school父组件
    const school1 = Vue.extend({
      name:'school1',
      template:`
        <div>
        <h2>学校名称:{{name}}</h2>
        <h2>学校地址:{{address}}</h2>
        <student></student>
        </div>
      `,
      data(){
        return{
          name:'长治学院',
          address:'长治'
        }
      },
      // 注册组件(局部)
      components:{
        student
      }
    })
    const school2 = Vue.extend({
      template:`
        <div>
          <h2>学校名称:{{name}}</h2>
          <h2>学校地址:{{address}}</h2>
        </div>
      `,
      data(){
        return{
          name:'北京大学',
          address:'北京'
        }
      },
/*      // 注册组件(局部)
      components:{

      }*/
    })
    // 定义app组件
    const app = Vue.extend({
      template:`
        <div>
          <school1></school1>
          <school2></school2>
        </div>
      `,
      components:{
        school1,
        school2
      }

    })

    // 创建vm
    new Vue({
      el:'#root',
      // 注册组件(局部)
      components:{
        app
      }

    })
  </script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

博客zhu虎康

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值