vue2.0父子组件传值

在vue开发中,我们经常需要在子组件使用父组件的数据,父组件使用子组件的数据,其实vue提供了这两个方法。

1.子组件向父组件传值,

在父组件内声明变量,子组件接受用props:

例如.父组件: 

复制代码
<template>
<div>
{{message }}{{num}}
<br />
<hello :num="num"></hello>
</div>
</template>
<script>
import hello from "@/components/HelloWorld"
export default {
data(){
return{
message:"我是父组件我要传的值是:",
num:10,
}
},
components:{
hello
}
}
</script>
复制代码

注册组件后在组件标签绑定你要传的值。

子组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<template>
    <div>
    {{message}}{{num}}
    </div>
</template>
<script>
    export default {
        //接受父元素的值用props
            props:["num"],
        data(){
            return{
            message:"我是子组件我接受的值是:",
            }
        },
    }
</script>

  子组件用props接受。结果如图所示

2.子组件向父组件传值

先在子组件定义,用$emit(),接受两个参数,一个是事件名,也就是绑定在父组件的事件,第二个是传的值,我把这个方法绑定在一个button按钮上,点击按钮传值。

子组件:

复制代码
<template>
    <div>
    {{message2}}{{count}}
    <br />
    <button @click="chuanzhi">像父组件传值</button>
    </div>
</template>
<script>
    export default {
        data(){
            return{
            message2:"我是子组件我要传的值是:",
            count:20
            }
        },
        methods:{
            chuanzhi(){
                //向父元素传值用$emit
            this.$emit("child",this.count);
            }
        }
    }
</script>
复制代码

父组件先定义一个空值num2,当点击的时候去用num2接收子组件传过来的值,把子组件的方法绑定在注册的子组件标签上。代码如下

父组件:

复制代码
<template>
    <div>
    {{message }}{{num2}}
    <br />
    <hello @child="getvalue"></hello>
    </div>
</template>
<script>
    import hello from "@/components/HelloWorld"
    export default {
        data(){
            return{
            message:"我是父组件我接受的值是:",
            num2:''
            }
        },
        components:{
            hello
        },
        methods:{
            getvalue(val){
                this.num2=val;
            }
        }
    }
</script>
复制代码

点击按钮,父组件接受的值为20.

 

 

 

posted @   zhupan  阅读(462)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示