我试图将数据从一个组件发送到另一个组件而没有任何成功。我有一个父组件 App.vue 和两个子组件 Base.vue 和 Ingredients.vue 。主要是我'想要将动态 {{selectedBase.price}} (每次选择/取消选择时更新)从Base组件发送到Ingredients组件,并动态呈现在Ingredients组件上。
我在main.js文件中导入并定义了 my-base 和 my-ingredients 组件
//App.vue
<v-app light>
<main>
<v-container fluid>
<v-flex xs12 sm6 offset-sm3>
<my-base ></my-base>
</v-flex>
<v-flex d-flex xs12 sm6 offset-sm3 class="text-xs-center">
<my-ingredients></my-ingredients>
</v-flex>
</v-container>
</main>
</v-app>
//Ingredients.vue
<v-layout row v-for="ingredient in ingredients" :key="ingredient.id">
<v-layout column>
<v-flex xs6 offset-xs5>
<v-checkbox class="text-xs-right" name="checkbox" color="light-blue lighten-2" v-bind:label="`${ingredient.name}`" v-model="ingredient.checked" light></v-checkbox>
</v-flex>
</v-layout>
<v-layout column>
<v-flex xs6 offset-xs5>
<v-subheader>{{ingredient.price}} €</v-subheader>
</v-flex>
</v-layout>
</v-layout>
<v-divider></v-divider>
<v-layout row wrap class="mb-3">
<v-layout column>
<v-flex xs6 offset-xs3>
<h3 class="headline mb-0">Total price:</h3>
</v-flex>
</v-layout>
<v-layout column>
<v-flex xs6 offset-xs4>
<v-subheader> {{total}} €</v-subheader>
</v-flex>
</v-layout>
</v-layout>
<script>
export default {
data: () => ({
checked1: '',
showCart: false,
ingredients: [{
id: 1,
name: "Mozzarella",
price: 2,
checked: '',
}, {
id: 2,
name: "Cheddar",
price: 2.0,
checked: '',
}, {
id: 3,
name: "Bacon",
price: 2.25,
checked: '',
}, {
id: 4,
name: "Mushrooms",
price: 1.6,
checked: '',
}, {
id: 5,
name: "Pepperoni",
price: 2.5,
checked: '',
}, {
id: 6,
name: "Sucuk",
price: 2.75,
checked: '',
}],
}),
computed: {
total: function() {
var total = 0;
for (var i = 0; i < this.ingredients.length; i++) {
if (this.ingredients[i].checked) {
total += this.ingredients[i].price;
}
}
return total;
}
}
}
</script>
//Base.vue
<v-layout row wrap primary-title v-for="base in bases" :key="base.id">
<v-layout column>
<v-flex xs6 offset-xs3>
<v-avatar size="80px" class="grey lighten-1">
<img :src="base.href" :class="{selected: selectedBase.id == base.id}" @click="selectedBase = base" alt="avatar">
</v-avatar>
</v-flex>
</v-layout>
<v-layout column>
<v-flex xs6 offset-xs4>
<v-subheader>{{base.name}} {{base.price}}€ {{selectedBase.price}}</v-subheader>
</v-flex>
</v-layout>
</v-layout>
</v-card>
</template>
<script>
export default {
data() {
return {
selectedBase: {},
bases: [{
id: 1,
name: "Margarita",
price: 4,
href: "../../static/margarita.jpg"
}, {
id: 2,
name: "Salami",
price: 6,
href: "../../static/salami.jpg"
}]
}
},
computed: {
totalBase() {
var totalBase = 0;
for (var i = 0; i < this.bases.length; i++) {
if (this.bases[i].selected) {
totalBase += this.bases[i].price;
}
}
return totalBase;
},
methods: {
getSelectedBase() {
return this.selectedBase;
}
}
}
}
</script>