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>
  • 相关阅读:
    Composite in Javascript
    Model Validation in Asp.net MVC
    HttpRuntime.Cache vs. HttpContext.Current.Cache
    Controller Extensibility in ASP.NET MVC
    The Decorator Pattern in Javascript
    The Flyweight Pattern in Javascript
    Model Binding in ASP.NET MVC
    Asp.net MVC
    jQuery Ajax 实例 全解析
    ASP.NET AJAX入门系列
  • 原文地址:https://www.cnblogs.com/maycpou/p/14736768.html
Copyright © 2011-2022 走看看