zoukankan      html  css  js  c++  java
  • vue 父子组件的方法调用

    $emit 子组件触发父组件的方法:

     1 <!-- 子组件 -->
     2 <template>
     3     <div id="child">
     4         <button @click="tryToParent">click</button>
     5     </div>
     6 </template>
     7 <script>
     8 export default {
     9     name: 'child',
    10     methods:{
    11         tryToParent(){
    12             // 通过$emit进行触发
    13             // 第一个参数为父组件监听的事件名,后续参数为父组件方法的参数
    14             this.$emit("toParent","我从子组件传来")
    15         }
    16     }
    17 }
    18 </script>
    19 
    20 <!-- 父组件 -->
    21 <template>
    22     <div id="parent">
    23         <!-- 监听child的toParent事件广播,用fromChild进行处理 -->
    24         <child @toParent="fromChild"></child>
    25     </div>
    26 </template>
    27 <script>
    28 import child from "./child.vue"
    29 export default {
    30     name: 'parent',
    31     components:{child},
    32     methods:{
    33         fromChild(msg){
    34             console.log(msg);  // 点击子组件的button,这里最终打印出“我从子组件传来”
    35         }
    36     }
    37 }
    38 </script>

    $refs 父组件获取子组件实例,进而调用子组件方法或者直接修改子组件属性:

     1 <!-- 子组件 -->
     2 <template>
     3     <div id="child">
     4         <div>{{message1}}</div>
     5         <div>{{message2}}</div>
     6     </div>
     7 </template>
     8 <script>
     9 export default {
    10     name: 'child',
    11     data(){
    12         return {
    13             message1:"",
    14             message2:""
    15         }
    16     },
    17     methods:{
    18         fromParent(msg){
    19             this.message1 = msg
    20         }
    21     }
    22 }
    23 </script>
    24 
    25 <!-- 父组件 -->
    26 <template>
    27     <div id="parent">
    28         <button @click="toChild">click</button>
    29         <child ref="child"></child>
    30     </div>
    31 </template>
    32 <script>
    33 import child from "./child.vue"
    34 export default {
    35     name: 'parent',
    36     components:{child},
    37     methods:{
    38         toChild(){
    39             /** this.$refs.child返回child组件实例 **/
    40 
    41             // 调用子组件的fromParent方法
    42             this.$refs.child.fromParent("我从父组件传递过来")
    43             // 直接修改child的data
    44             this.$refs.child.message2 = "啦啦啦"
    45         }
    46     }
    47 }
    48 </script>

      在复杂的vue应用中,应该用vuex的store来管理跨组件的数据交流,再根据数据的变化触发相应的方法。

  • 相关阅读:
    C/C++ 语言中的表达式求值
    C++中delete与delete[]
    特殊数据类型成员变量的初始化
    C++中的new
    C++数组名解析
    C++中的位拷贝和值拷贝
    while(cin>>s)退出问题
    C++继承中的虚析构函数
    C++的IO标准库介绍
    C++一道面试题(atexit)
  • 原文地址:https://www.cnblogs.com/yangshifu/p/9518528.html
Copyright © 2011-2022 走看看