vue学习笔记7 -组件之 父子组件之间的访问

$children和$refs的使用

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>New Web Project</title>
        <script src="vue.js"></script>
    </head>
    
    <body>
        <div id="app">
         <cpn></cpn>
         <cpn></cpn>
         <cpn ref='aaa'></cpn>
         <button @click="btnClick">实例</button>
         
        </div>
    </body>
    
  <!--子组件模板-->
  <template id='cpn'>
    <div>
      <h2>我的子组件</h2>
    </div>
    
  </template>

  <script>
  const app = new Vue({
    el:"#app",
    data:{
      message:'你好啊'
    },
    components:{
      cpn:{
        template:"#cpn",
        
        data(){
          return {
            name:'我是子组件的data属性'
          }
        },
        methods:{
          showMessage:function(){
            console.log('showMessage')
          }
        },
        
      }
    },
    methods:{
      btnClick(){
        //console.log(this.$children)
        /*
        this.$children[0].showMessage()
                 console.log(this.$children[1].name)*/
        // console.log(this.$refs.aaa.name)
        this.$refs.aaa.showMessage()
      }
    }
  })
  </script>
</html>
View Code

猜你喜欢

转载自www.cnblogs.com/polax/p/12934584.html