the case
Code of parent component:
Passing values to child components via property binding
<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>
First, the data requested by the known backend is an array
And how axios requests backend data
Subassembly
Child components accept via props attribute
<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>
page display
renderings
When we click a random + button, such as clicking the first + sign
Interface changes:
It is obvious that the total price of the menu in the child component has changed, but the total price of the parent component has not changed
Note: attribute value transfer is one-way