vue.js之父子组件通信方式三($parent和$children)

父子组件通信方式三

  • 父子组件通信方式一 (props/$emit
  • 父子组件通信方式二 (ref/$refs
  • $parent 获取当前组件的父组件实例
  • $children 获取当前组件的子组件实例
  • 不推荐使用这种方式进行组件通信
  • 案例父组件传给子组件title,在父子间里获取子组件的实例和数据
  • 子组件
<template>
    <div>
        <h1>
            {{title}}
            <button @click="handleClick">emit</button>
        </h1>
        child
    </div>
</template>
<script>
    export default {
        props: ["title"],
        methods: {
            getTitle() {
                return this.title
            },
            handleClick(){
                this.$emit("child","123");
            }
        },
    }
</script>
<style lang="scss" scoped>
</style>
  • 父组件
<template>
    <div>
        Parent
        <Child title="my name is Parent" @child="handleChild"></Child>
    </div>
</template>
<script>
import Child from "./Child";
    export default {
        components: {
            Child,
        },
        mounted () {
        	// 获取子组件title
            // console.log(this.$children[0].title);
            // 修改子组件的title,会有警告
            this.$children[0].title = "pass children set value"; 
            console.log(this.$children[0].getTitle());
        },
        methods: {
            handleChild(msg) {
                console.log(msg);
            }
        },
    }
</script>
<style lang="scss" scoped>
</style>

vue.js之父子组件通信方式三($parent和$children)_第1张图片

你可能感兴趣的:(vue.js,前端,vue.js,父子组件通信)