0
点赞
收藏
分享

微信扫一扫

56 组件通信和生命周期

小月亮06 2022-01-08 阅读 109

56 组件通信和生命周期

父子组件通信

父传子
<div id="#app">
    <father></father>
</div>
Vue.component("father", {
    template:`<div>
		<h4>父级</h4>
		<son msg="message"></son>
	</div>`,
    components: {
        son: {
            template: `<div>
				<h5>子级</h5>
				<p>{{ msg }}</p>
			</div>`,
        },
        props: {
            msg: {
                type: String,
            }
        }
    },
    data() {
        return {
            message: "父级数据"
        }
    },
})
new Vue({
	el: "#app"
})
子传父
<div id="#app">
    <father></father>
</div>
Vue.component("father", {
    template:`<div>
		<h4>父级</h4>
		<son @father="son"></son>
		<p>{{ message }}</p>
	</div>`,
    components: {
        son: {
            template: `<div>
				<h5 @click="handle">子级</h5>
			</div>`,
        },
        data() {
            return {
                message: "子级数据"
            }
        },
        methods: {
            handle() {
                this.$emit("father", this.message)
            }
        }
    },
    data() {
        return {
            message: "父级数据"
        }
    },
    methods: {
        son(data) {
            this.message = data
        }
    }
})
new Vue({
	el: "#app"
})

跨组件层级通信

<div id="#app">
    <father></father>
</div>
const bus = new Vue()
Vue.component("father", {
    template:`<div>
		<h4 @click="father">父级</h4>
		<son></son>
		<p>{{ message }}</p>
	</div>`,
    components: {
        son: {
            template: `<div>
				<h5 @click="son">子级</h5>
			</div>`,
        },
        data() {
            return {
                message: "子级数据"
            }
        },
        methods: {
            son() {
                bus.$emit("toFather", this.message)
            }
        }
    },
    data() {
        return {
            message: "父级数据"
        }
    },
    methods: {
        father() {
            bus.$on("toFather", handle)
        },
        handle(data) {
            this.message = data
        }
    }
})
new Vue({
	el: "#app"
})

生命周期

create 阶段
mount 阶段
update 阶段
destroy阶段

el被新创建的vm.$el` 替换了

update 阶段
destroy阶段
举报

相关推荐

0 条评论