接上一篇 vue 组件传值 (一): 父组件向子组件传值 https://www.example.com/
第二种情况: children to parents
父组件 Component
- <template>
- <!-- 所有的内容要被根节点包含起来 -->
- <div id="home">
- <v-header ref="header"> 首页组件 </v-header>
- <button @click="getChildData()"> 获取子组件的数据和方法 </button>
- </div>
- </template>
- <script>
- /*
- 父组件主动获取子组件的数据和方法:
- 1. 调用子组件的时候定义一个 ref
- <v-header ref="header"></v-header>
- 2. 在父组件里面通过
- this.$refs.header. 属性
- this.$refs.header. 方法
- 子组件主动获取父组件的数据和方法:
- this.$parent. 数据
- this.$parent. 方法
- */
- import Header from './Header.vue';
- export default{
- data(){
- return {
- msg:'我是一个 home 组件',
- title:'首页 111'
- }
- },
- components:{
- 'v-header':Header
- },
- methods:{
- run(){
- alert('我是 Home 组件的 run 方法');
- },
- getChildData(){
- // 父组件主动获取子组件的数据和方法:
- alert(this.$refs.header.msg);
- this.$refs.header.run();
- }
- }
- }
- </script>
子组件 Component
- <template>
- <div>
- <h2 > 我是头部组件 </h2>
- <button @click="getParentData()"> 获取子组件的数据和方法 </button>
- </div>
- </template>
- <script>
- export default{
- data(){
- return{
- msg:'子组件的 msg'
- }
- },
- methods:{
- run(){
- alert('我是子组件的 run 方法')
- },
- getParentData(){
- /*
- 子组件主动获取父组件的数据和方法:
- this.$parent. 数据
- this.$parent. 方法
- */
- alert(this.$parent.msg);
- this.$parent.run();
- }
- }
- }
- </script>
- </style>
来源: http://www.qdfuns.com/article/35195/6e73622606cfe6117da3dd46149e2496.html