创建组件components/MyProduct.vue - 复制下面标签
组件内在props定义变量, 用于接收外部传入的值
App.vue中引入注册组件, 使用时, 传入具体数据给组件显示
components/MyProduct.vue - 准备标签
<template> <div class="my-product"> <h3>标题: {{ title }}</h3> <p>价格: {{ price }}元</p> <p>{{ intro }}</p> </div> </template> <script> export default { props: ['title', 'price', 'intro'] } </script> <style> .my-product { width: 400px; padding: 20px; border: 2px solid #000; border-radius: 5px; margin: 10px; } </style>
App.vue中使用并传入数据
<template>
<div>
<!--
目标: 父(App.vue) -> 子(MyProduct.vue) 分别传值进入
需求: 每次组件显示不同的数据信息
步骤(口诀):
1. 子组件 - props - 变量 (准备接收)
2. 父组件 - 传值进去
-->
<Product title="好吃的口水鸡" price="50" intro="开业大酬宾, 全场8折"></Product>
<Product title="好可爱的可爱多" price="20" intro="老板不在家, 全场1折"></Product>
<Product title="好贵的北京烤鸭" price="290" :intro="str"></Product>
</div>
</template>
<script>
// 1. 创建组件 (.vue文件)
// 2. 引入组件
import Product from './components/MyProduct'
export default {
data(){
return {
str: "好贵啊, 快来啊, 好吃"
}
},
// 3. 注册组件
components: {
// Product: Product // key和value变量名同名 - 简写
Product
}
}
</script>
<style>
</style>
子向父
语法:
-
父: @自定义事件名="父methods函数"
-
子: this.$emit("自定义事件名", 传值) - 执行父methods里函数代码
components/MyProduct_sub.vue
<template> <div class="my-product"> <h3>标题: {{ title }}</h3> <p>价格: {{ price }}元</p> <p>{{ intro }}</p> <button @click="subFn">宝刀-砍1元</button> </div> </template> <script> import eventBus from '../EventBus' export default { props: ['index', 'title', 'price', 'intro'], methods: { subFn(){ this.$emit('subprice', this.index, 1) // 子向父 eventBus.$emit("send", this.index, 1) // 跨组件 } } } </script> <style> .my-product { width: 400px; padding: 20px; border: 2px solid #000; border-radius: 5px; margin: 10px; } </style>
App.vue
<template> <div> <!-- 目标: 子传父 --> <!-- 1. 父组件, @自定义事件名="父methods函数" --> <MyProduct v-for="(obj, ind) in list" :key="obj.id" :title="obj.proname" :price="obj.proprice" :intro="obj.info" :index="ind" @subprice="fn" ></MyProduct> </div> </template> <script> import MyProduct from './components/MyProduct_sub' export default { data() { return { list: [ { id: 1, proname: "超级好吃的棒棒糖", proprice: 18.8, info: "开业大酬宾, 全场8折", }, { id: 2, proname: "超级好吃的大鸡腿", proprice: 34.2, info: "好吃不腻, 快来买啊", }, { id: 3, proname: "超级无敌的冰激凌", proprice: 14.2, info: "炎热的夏天, 来个冰激凌了", }, ], }; }, components: { MyProduct }, methods: { fn(index, price) { const currentPrice = this.list[index].price; currentPrice > 1 && (this.list[index].price = (currentPrice - price).toFixed(2)); }, } }; </script> <style> </style>