Vue(13)子组件与父组件超详细解析

父组件和子组件

我们经常分不清什么是父组件,什么是子组件。现在来简单总结下:我们将某段代码封装成一个组件,而这个组件又在另一个组件中引入,而引入该封装的组件的文件叫做父组件,被引入的组件叫做子组件。具体代码如下

<div id="app">
  <component2></component2>
</div>
<script>
  // 全局注册
  Vue.component("component1", {
    template: `
    <div>
      <h2>hello</h2>
    </div>
    `
  })

  const app = new Vue({
    el: "#app",
    data: {
      message: "hello"
    },
    components: {
      // 局部注册
      "component2": {
        template: `
            <div>
              <component1></component1>
              <h2>world</h2>
            </div>
        `,
      }
    }
  })
</script>

1.全局注册组件component1
2.局部注册组件component2component2中又引用了组件component1

最后我们在html中使用组件component-2,模板代码就是

<div>
  <component-1></component-1>
  <h2>world</h2>
</div>

又因为组件component1中也有模板,所以程序会自动进行解析,最后component-2html代码为

<div>
  <div>
      <h2>hello</h2>
    </div>
  <h2>world</h2>
</div>

所以我们在浏览器上看到的效果应该是:

hello
world

结果component1是子组件,component2是父组件

模板分离写法

上面我们创建组件的时候,都在组件中写了模板template,但是在编译器里这样写,不仅没有代码提示,而且换行也不对齐,写起来很麻烦,所以这里介绍模板分离写法

template标签

我们将原来在组件里写的template模板抽离出来,放在html中,使用template标签,并且给他附上id属性如下:

<template id="component2">
  <div>
    <component1></component1>
    <h2>world</h2>
  </div>
</template>

然后在组件中,将原来template标签的内容换成id,这样程序就会自动去寻找对应的id模板:

components: {
  // 局部注册
  "component2": {
    template: `#component2`,
  }
}

推荐这种写法

text/x-template

我们还有另一中写法,跟上面差不多,上面我们用的template标签,此写法只需将template中的内容放到script标签中,并给与类型type=text/x-template,再给上一个id属性即可,如下:

<script type="text/x-template" id="component2">
  <div>
    <component1></component1>
    <h2>world</h2>
 
  • 19
    点赞
  • 57
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值