案例
父组件的代码:
通过属性绑定将值传入子组件
<template> <div> <!--首先用v-for循环把值遍历出来 ,同时通过属性绑定将父组件的值传入子组件 --> <Box v-for="el,index in arr" :title="el.title" :price="el.price" :count="el.count" :key="el.id" ></Box> <button>{ {msg}}:{ {total}}</button> </div> </template> <script> import Box from "@/components/myheader.vue" //引入子组件 export default { name: 'VueApp', data() { return { msg:"父组件的总价", arr:[] //必须提前给后端数据创建一个数据容器,不然在数据请求过来之前会出错 }; }, components:{ Box }, async mounted() { let res= await this.$axios("/test") //页面挂载的时候请求的后端数据 this.arr=res.data //将后端数据保存起来 console.log(this.arr) }, methods: { }, computed:{ total(){ //父组件计算总价 return this.arr.reduce((n1,n2)=>{ return n1+n2.price*n2.count },0) } } }; </script> <style scoped> </style>
首先已知后端请求的数据为一个数组
子组件
子组件通过props属性接受
<template> <div> 菜名:{ {title}}, 数量:{ {count}} <button @click="add">+</button> , 价格:{ {price}}元 单菜总价:{ {total}}元 </div> </template> <script> export default { name: 'VueBox', props:['title','price','count'], // 使用props属性接受父组件的值 data() { return { }; }, mounted() { }, computed:{ total(){ return this.count*this.price //计算单样菜品的总价 } }, methods: { add(){ this.count++ //点击事件,让菜品数量增加 } }, }; </script> <style scoped> </style>
页面展示
效果图
当我们点击随机点击一个+按钮时,如点击第一个+号
界面变化:
很明显能力看出在子组件中的单菜总价变化了,而父组件的总价依旧没有改变
说明:属性传值是单向的