vue 组件间传值的几种方式
一、子组件更改父组件数据
(1)props传递方法
通过props的方式,将父组件的方法传递到子组件,在子组件中通过props接收,可以在当前组件的实例上直接触发父组件的方法,从而实现子组件更改父组件的值。同事也可以将子组件的数据,以参数的形式发送给父组件。
<!--
父组件,设置更改自己数据的方法,将该方法传递给子组件
-->
<template>
<div class="home">
<h1>我是父组件</h1>
<HelloWorld :msg="msg" :changeMsg="changeMsg"/>
</div>
</template>
<script>
import HelloWorld from '@/components/HelloWorld.vue'
export default {
name: 'Home',
components: {
HelloWorld
},
methods:{
changeMsg(text,num){
console.log(text,num);
this.msg=this.msg+1
}
},
data(){
return{
msg:1
}
}
}
</script>
<!--
子组件,接收父组件传递过来的方法,通过props接收到的方法和数据,在组件实例上可以直接获取和触发
-->
<template>
<div class="hello">
<h1>我是子组件<button @click="changeFatherData">点我更改父组件数据</button></h1>
<h1>父组件数据:{{msg}}</h1>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: Number,
changeMsg:Function
},
data(){
return{
text:"我是子组件数据,我要发送给父组件",
num:12
}
},
methods:{
changeFatherData(){
this.changeMsg(this.text,this.num)
}
},
}
</script>
<style scoped lang="scss">
</style>
(2)通过this.$emit触发父组件方法实现
在父组件中自定义一个方法,然后传递给子组件,子组件通过this.$emit直接触发父组件中的数据,实现父子组件通信。子组件触发事件,父组件监听事件。
<!--
父组件,将定义的方法传递给子元素
-->
<template>
<div class="home">
<h1>我是父组件</h1>
<HelloWorld :msg="msg" @changeMsg="changeMsg"/>
</div>
</template>
<script>
import HelloWorld from '@/components/HelloWorld.vue'
export default {
name: 'Home',
components: {
HelloWorld
},
methods:{
changeMsg(text,num){
console.log(text,num);
this.msg=this.msg+1
}
},
data(){
return{
msg:1
}
}
}
</script>
<!--
子组件,通过this.$emit触发父组件方法,更改父组件数据,同时可以进行数据传值
-->
<template>
<div class="hello">
<h1>我是子组件<button @click="changeFatherData">点我更改父组件数据</button></h1>
<h1>父组件数据:{{msg}}</h1>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: Number,
},
data(){
return{
text:"我是子组件数据,我要发送给父组件",
num:12
}
},
methods:{
changeFatherData(){
this.$emit('changeMsg',this.text,this.num)
}
},
}
</script>
<style scoped lang="scss">
</style>
二、父组件修改子组件的值
(1)可以通过ref的方式调用子组件的方法改变子组件的值
props只支持第一次加载这个组件的时候获取父组件的值,后续修改父组件的值得时候子组件并不会动态的更改。
可以通过ref的方式调用子组件的方法改变子组件的值。
<!--
子组件
-->
<template>
<div>
<span>{{data}}</span>
</div>
</template>
<script>
export default {
data() {
return {
data:'就要被修改啦'
};
},
methods: {
a(val) {
this.data=val;
},
},
};
</script>
<!--
父组件
-->
<template>
<div>
<child ref='child'></child>
</div>
</template>
<script>
export default {
mounted(){
setTimeout(()=>{
this.$refs.child.a("把你修改了");
},3000)
}
components:{
child:()=>import("../components/child.vue")
}
};
</script>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
2018-08-03 还原一直卡在ASYNC_IO_COMPLETION浅析