vue中子组件调用父组件里面的数据和方法 父组件调用子组件的数据和方法
1.子组件直接调用父组件的数据和方法
在父组件father,vue
<template> <div> <!-- 父组件里面的数据 --> <p>父组件里面的数据{{data}}</p> <!-- 父组件里面的方法 --> <p click="test">父组件里面的方法方法方法方法</p> <!-- 使用组件 --> <child></child> </div> </template> <script> import child from './components/child.vue'// 引入子组件 export default { components:{ //注册组件 child }, data(){ return{ data:'我的父组件data' } }, methods:{ test(){ console.log('点击了父组件') } } } </script>
下面在子组件中调用父组件的数据和方法
<template> <div> <button @click="toFather">我是子组件 {{this.$parent.data}}</button> <!-- this.$parent.data获取父组件的数据 --> </div> </template> <script> export default { data(){ return{} }, methods:{ toFather() { // 直接通过this.$parent.test()获取方法 this.$parent.test() } } } </script>
总结:
直接在子组件中 this.$parent.prop 调用的数据
this.$parent.fn() 调用的方法
2.父组件直接调用子组件的数据和方法
父组件调用子组件的地方,添加一个ref的属性,属性值任意定义 即在父组件组件中 father.vue
<template> <div> 我是父组件 <!--调用子组件组件 添加ref属性 --> <child ref="getdata"></child> <button @click="getChild">点击按钮获取子组件的数据msg</button> </div> </template> <script> import child from './components/child.vue'// 引入子组件 export default { components:{ //注册组件 child }, data(){ return{ } }, methods:{ getChild(){ // this.$refs.getdata.msg 拿到数据 console.log(this.$refs.getdata.msg) } } } </script>
child.vue的数据
<template> <div> <button>我是子组件</button> </div> </template> <script> export default { data(){ return{ msg:'我是子组件数据' } }, methods:{ } } </script>
总结:
父组件调用子组件的地方,添加一个ref的属性,属性值任意定义
父组件某一个事件中,可以通过this.$refs.test.prop拿到子组件的数据,可以通过this.$refs.test.fn()调用子组件的方法
- 上一篇 »vue 子组件跨多层调用父组件中方法
- 下一篇 »Vue组件之从外部获取数据