Vue父子组件之间的属性访问之children,refs,parent,root方法

父访问子:

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Document</title>

</head>

<body>

  <div id="app">

    <cpn></cpn>

    <cpn ref="aaa"></cpn>

    <cpn></cpn>

    <button @click="btnClick">按钮</button>

  </div>

  <template id="cpn">

    <div>

      <h2>我是子组件</h2>

    </div>

  </template>

  <script src="../../js/vue.js"></script>

  <script>

    const app  = new Vue({

      el: "#app",

      data: {

      },

      components:{

        cpn: {

          template: '#cpn',

          data() {

            return {

              name: "我是子组件的name"

            }

          },

          methods: {

            showMessage() {

              console.log('我是子组件')

            }

          },

        }

      },

      methods: {

        btnClick() {

          // 父访问子方法:$children(一般不使用这种方法,因为组件数量在变化,用下标容易发生混乱)

          // console.log(this.$children),

          // this.$children[0].showMessage()

          // for(item of this.$children){

          //   console.log(item.showMessage())

          // }

          // $refs,需在使用父组件时定义其键名,一般使用这个

          console.log(this.$refs.aaa.name,this.$refs.aaa.showMessage());

          // console.log(this.$refs.aaa.showMessage())

        }

      },

    })

  </script>

</body>

</html>

子访问父

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Document</title>

</head>

<body>

  <div id="app">

    <cpn></cpn>

  </div>

  <template id="cpn">

    <div>

      <h2>我是子组件</h2>

      <ccpn></ccpn>

    </div>

  </template>

  <template id="ccpn">

    <div>

      <h2>我是孙组件</h2>

      <button @click="btnClick">按钮</button>

    </div>

  </template>

  <script src="../../js/vue.js"></script>

  <script>

    const app  = new Vue({

      el: "#app",

      data: {

        name: "我是顶层的name"

      },

      components:{

        cpn: {

          template: '#cpn',

          data() {

            return {

              name: "我是子组件的name"

            }

          },


          components:{

            ccpn: {

              template: '#ccpn',

              methods: {

                btnClick() {

                  // $parent访问的是组件上一层的属性

                  console.log(this.$parent.name),

                  // $root访问的是顶层组件的属性,两种方法都很少用,因为要避免耦合

                  console.log(this.$root.name)

                }       

              },

            }

          }

        }

      },


    })

  </script>

</body>

</html>

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容