复习vue(9)组件嵌套

162 阅读1分钟

「这是我参与2022首次更文挑战的第23天,活动详情查看:2022首次更文挑战」。

组件嵌套

为什么会嵌套?

  • 父组件使用了子组件,而子组件又使用了孙子组件,即a功能依赖于b组件,b组件依赖c组件;
  • 创建一个组件 => 只对应的父组件进行注册 => 在父组件的标签中直接嵌套子组件的标签名;
代码示例:
// grandson 组件

<template>
  <div id="grn">{{name}}</div>
</template>

<script>
export default {
  name: 'grn',
  data () {
    return {
      name:"孙子"
    }
  }
}
</script>


// son 组件

<template>
  <div id="hello">
    {{name}}
    <grandson></grandson>
  </div>
</template>

<script>
import grandson from './grandson.vue';
export default {
  name: 'hello',
  data () {
    return {
      name:"儿子"
    }
  },
  components:{
    grandson
  }
}
</script>


代码示例:
// 最终父组件

<template>
  <div id="app">
    {{name}}
    <son></son>
  </div>
</template>

<script>
import son from "./components/son.vue";

export default {
  name: "App",
  data() {
    return {
      name: "爸爸",
    };
  },
  components: {
    son,
  },
};
</script>

动态组件

有的时候,在不同的组件之间进行动态切换是非常有用的,此时就需要用到动态组件;

实现动态组件

动态组件:
需要使用内置的 component 组件
<component :is="title"></component> 在这个组件上有一个 is 属性,动态绑定该属性,当被绑定的值发生变化时,vue会渲染 is 最新的值对应的组件;

代码示例:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>

<body>

  <div id="app">
    <label>HOME <input type="radio" value="home" v-model="title"></label>
    <label>List <input type="radio" value="list" v-model="title"></label>
    <component :is="title"></component>
  </div>

  <script src="vue.js"></script>
  <script>
    //   创建组件
    //   动态组件在进行切换时,会将上一个组件销毁,然后再挂载最新的组件
    //   动态组件,需要使用内置的 component 组件 // <component :is="title"></component>
    //   在这个组件上有一个 is 属性,动态绑定该属性,当被绑定的值发生变化时,Vue 会渲染 is 最新的值对应的组件;
    let home = {
      template: `<div>HOME <input type="text" v-model="home"></div>`,
      data() {
        return {
          home: ''
        }
      },
      mounted() {
        console.log('挂载home')
      },
      destroyed() {
        console.log('home销毁')
      }
    };

    let list = {
      template: `<div>LIST <input type="text" v-model="list"></div>`,
      data() {
        return {
          list: ''
        }
      },
      mounted() {
        console.log('list挂载')
      },
      destroyed() {
        console.log('list销毁')
      }
    };

    let vm = new Vue({
      el: '#app',
      data: {
        title: 'home'
      },
      components: {
        home,
        list
      }

    })
  </script>
</body>

</html>