美文网首页前端技术
Vue父组件主动获取子组件的数据和方法

Vue父组件主动获取子组件的数据和方法

作者: 剑有偏锋 | 来源:发表于2018-07-31 17:45 被阅读1410次

一 创建测试项目

vue init webpack-simple vuedemo

二 进入demo目录

cd vuedemo

三 安装依赖

cnpm install

四 修改代码

要修改的文件
要修改的文件
├── src
│ ├── App.vue
│ ├── components
│ │ ├── Header.vue
│ │ └── Home.vue

App.vue

<template>
  <div id="app">
<v-home></v-home>
<hr>
  </div>
</template>

<script>
/*
import components
Local Registration components
use in template
*/

import Home from './components/Home.vue';

export default {
  name: "app",
  data() {
    return {
      msg:'hello vue world!',     
    };
  },
  components:{
    'v-home':Home
  },
};
</script>

<style>

</style>

Header.vue

<template>
    <div>
       <button @click="getParentData()">getParentDataFromeHeader</button>
    </div>
</template>


<script>
export default {
    data(){
        return{
            msg:'subcomponents msg!'
        }
    },
    methods:{
        run(){
            console.log("i am function in subcomponents")           
        },
        getParentData(){
            console.log("this call from subcomponent" + this.$parent.msg)

            this.$parent.run("888");
        }
    }   
}
</script>

Home.vue

<template>
    <!-- all content need in root-->
    <div id="home">
        <v-header ref="header"></v-header>
       {{msg}}
       <button @click="getChildData()">getChildData</button>
       <br>
       <hr>
    </div>
</template>


<script>

import Header from './Header.vue'

export default {
    data(){
        return {
            msg:'i am home component!',
        }
    },
    components:{
        'v-header': Header
    },
    methods:{
        run(msg){
            console.log("i am a function from Home components" + msg)
            
        },
        getChildData(){
            console.log(this.$refs.header.msg)
            this.$refs.header.run()
        }
    }
}
</script>

<style>

#home h2{
    color: red;
}
</style>

五 运行

npm run dev


image.png

六 总结

1 父组件主动获取子组件的数据
《1 父组件文件,使用子组件时,声明ref属性
<v-header ref="header"></v-header>
《2 父组件函数中,调用

this.$refs.header.属性
this.$refs.header.方法

备注:ref 被用来给元素或子组件注册引用信息。引用信息将会注册在父组件的 $refs 对象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子组件上,引用就指向组件实例:

2 子组件调用父组件属性和方法

《1 this.$parent.属性
《2 this.$parent.方法

七 参考

https://cn.vuejs.org/v2/guide/components-props.html
https://cn.vuejs.org/v2/api/#ref
https://cn.vuejs.org/v2/api/#vm-refs

相关文章

网友评论

    本文标题:Vue父组件主动获取子组件的数据和方法

    本文链接:https://www.haomeiwen.com/subject/udncvftx.html