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()調用子組件的方法