zoukankan      html  css  js  c++  java
  • vue(16)父子组件之间直接相互访问

    父子组件之间可以直接调用对方的方法和变量

    父组件:

    <template>
        <div>
          <button @click="parentClick">父组件按钮</button>
          <HelloWorld ref="firstChild"></HelloWorld>//给子组件起一个别名叫firstChild,因为父组件会有多个子组件需要别名来区分到底访问哪一个子组件的数据
        </div>
    </template>

    <script>
    import HelloWorld from './component/HelloWorld'

    export default {
       name:"App",
       data:function(){
           return {
            parentCount:1
           };
       },
       components:{
           HelloWorld
       },
       computed:{
           
       },
       methods:{
          parentFun(){
            console.log('this is parent component');
          },
          parentClick(){
            console.log(this.$refs.firstChild.childCount);//访问子组件的变量
            this.$refs.firstChild.childFun();//调用子组件的方法
          }
       }
    }
    </script>

    <style scoped>
    </style>

    子组件:

    <template>
    <div>
        <button @click="childClick">子组件按钮</button>
    </div>
    </template>

    <script>
    export default ({
        data:function(){
            return{
                childCount:2
            }
        },
        methods:{
            childClick(){
                console.log(this.$parent.parentCount);//访问父组件的变量
                this.$parent.parentFun();//调用父组件的方法
       //这里可以用 this.$parent.$parent...继续访问父组件的父组件...,可以使用this.$root访问根组件的数据
            },
            childFun(){
                console.log('this is child component');
            }
        }
    })
    </script>

    <style scoped>

    </style>
  • 相关阅读:
    IOS开发之XML解析以及下拉刷新上拉加载更多的分享
    iOS之网络数据下载和JSON解析
    iOS开发常用网站
    用shell脚本打ipa包
    iOS开发之网络基础知识
    iOS开发之Block
    iOS开发之用代码实现数据库FMDB的操作
    iOS开发之下拉刷新和上拉加载
    IOS之XML解析
    IOS之网络数据下载和JSON解析
  • 原文地址:https://www.cnblogs.com/maycpou/p/14736768.html
Copyright © 2011-2022 走看看