关于前端:vue-20-组件传值2

6次阅读

共计 881 个字符,预计需要花费 3 分钟才能阅读完成。

形容

1. 调用子组件的时候定义一个 ref

<v-header ref="header"></v-header>        

2. 在父组件外面通过

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

子组件被动获取父组件的数据和办法:

this.$parent. 数据
this.$parent. 办法 

父组件

<template>
    <div id="father">
        <slider-header ref="header"></slider-header>
        <hr>
         首页组件
        <button @click="getChildData()"> 获取子组件的数据和办法 </button>
    </div>
</template>

<script>
    import SliderHeader from './SliderHeader.vue';// 引入子组件
    export default{data(){
            return { // 父组件的值
               msg: '我是一个 father 组件',
               title: '首页'
            }
        },
        components:{'slider-header': SliderHeader// 绑定子组件},
        methods:{getChildData(){
                // 父组件被动获取子组件的数据和办法:console.log(this.$refs.header.msg);
            }
        }
    }
</script>

<style lang="scss" scoped>
    /*css scoped 设置 部分作用域  */
    h2{color:red} 
</style>

子组件 Header

<template>
    <div>
        <h2> 我是头部组件 --{{msg}}</h2>
        <button @click="getParentData()"> 获取子组件的数据和办法 </button>
    </div>
</template>

<script>    
export default{data(){
        return{msg: '子组件的 msg'}
    },
    methods:{getParentData(){
                // 子组件被动获取父组件的数据和办法:console.log(this.$parent.msg);
            }
    }
}
</script>
正文完
 0