vue~父组件与子组件的交互
我们在进行vue开发时会将公共的部分进行抽象,然后生成一个独立的组件,这个组件可以被其它页面引用,如果希望有交互的动作就设计到了值的传递,或者方法的回调等问题,这一次我们主要来说一下父组件和子组件的交互。
值的传递
子组件,通过定义了prods,然后可以实现从父组件向子组件的传递:
<template>
<div id="app">
这是自定义的组件:{{myMessage}}
<button @click="childClick">调用父组件的方法</button>
</div>
</template>
<script>
export default {
name: "testComponent",
props: ["myMessage"],
data() {
return {
message: "hello world",
myNum: 37,
myStr: "lind"
};
},
methods: {
childClick() {
console.log("调用childClick");
this.$emit("abcClick", this.myNum, this.myStr);
}
}
};
</script>
父组件/页面,直接为这个prods赋值即可,注意如果JS里props名称是小驼峰,在html需要用中线来代替
<testComponent my-message="hello"></testComponent>
<script>
import testComponent from "@/components/testComponent";
export default {
name: "test-grammer",
props: {
//接收父组件传递过来的参数
},
components: {
testComponent
}
}
</script>
方法的传递/回调
在父页面绑定子组件的方法,然后子组件在某个时机去触,这就形成了在子组件里调用父组件的方法,使用了$emit来实现
<button @click="childClick">调用父组件的方法</button>
<script>
export default {
name: "testComponent",
methods: {
childClick() {
this.$emit("abcClick", this.myNum, this.myStr);
}
}
};
</script>
在父页面中去绑定这个abcClick事件
就可以了,当在子组件调用这个childClick事件时,绑定了abcClick的方法将会被一起回调
<testComponent @abcClick="sayHello"></testComponent>
<script>
import testComponent from "@/components/testComponent";
export default {
name: "test-grammer",
methods: {
sayHello(Num, Str) {
console.log("hello world~~" + Num + Str);
}
},
};
</script>
合集:
前端技术
分类:
前端技术 / vue&react
, 前端技术
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
2017-06-26 docker~通过vs2017的Dockerfile来生成镜像
2014-06-26 JS~模拟表单在新窗口打开,避免广告拦截
2012-06-26 爱上MVC3系列~RenderAction与RenderPartial及一个页面多个表单提交