Vue学习-父子组件访问

父子组件访问

1.父访问子

  1. $children

  2. $refs

    
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Documenttitle>
    head>
    <body>
      <div id="app">
        <cpn>cpn>
        <cpn>cpn>
        <cpn>cpn>
        <cpn ref="reference">cpn>
        <button @click="btnClick">按钮button>
      div>
      <template id="cpn">
        <div>
          <h1>子组件h1>
        div>
      template>
      <script src="../js/vue.js">
      script>
      <script>
         const app = new Vue({
            el: '#app',
            data: {
              message: 'hello'
            },
            methods: {
              btnClick(){
              // 1.$children
              //  this.$children[0].showMessage();
              
              // $refs
              console.log(this.$refs.reference.name);
              }
    
            },
            components: {
              cpn: {
                template : '#cpn',
                data() {
                  return {
                    name: 'a',
                  }
                },
                methods: {
                  showMessage(){
                    console.log('showMessage');
                  }
                },
              },
            }
         })
      script>
    body>
    html>
    

2.子访问父

  1. $parent

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Documenttitle>
head>
<body>
  <div id="app">
    <cpn>cpn>
    
  div>
  <template id="cpn">
    <div>
      <h1>子组件h1>
      <ccpn>ccpn>
    div>
  template>
  <template id="ccpn">
    <div>
      <h1>cpn子组件h1>
      <button @click="btnClick">按钮button>

    div>
  template>
  <script src="../js/vue.js">
  script>
  <script>
     const app = new Vue({
        el: '#app',
        data: {
          message: 'hello'
        },
        methods: {
         
        },
        components: {
          cpn: {
            template : '#cpn',
            data() {
              return {
                name: 'a',
              }
            },
            methods: {
              
            },
            components: {
              ccpn: {
                template : '#ccpn',
                data() {
                  return {
                    
                  }
                },
                methods: {
                  btnClick(){
                  // 子访问父:$parent
                  console.log(this.$parent.name);
                  // 访问根组件: $root
                  console.log(this.$root.message);
                },
              }
            }

            },
          },
        }
     })
  script>
body>
html>

你可能感兴趣的:(Vue学习-父子组件访问)