说明
将 vue教程:全局组件(非单文件)-给组件传值(动态传值)-传数组 改写为单文件组件
代码
创建组件
与 vue教程:全局组件(非单文件)-给组件传值(动态传值) 相同
在 components 目录下创建文件:JdGoods2.vue,内容如下:
<template>
<div class="goods">
<div >
<img :src="img">
</div>
<div >
{{gname}}
</div>
<div>
¥{{price}}
</div>
</div>
</template>
<script>
export default{
name:"JdGoods2",
data: function(){ // 组件中的data必须是函数,必须返回 {} 对象
return { //数据
// img:'img/mate60.png',
// name:'华为R70 PRO',
// price:1700
}
},
props:["img","gname","price"]
}
</script>
<style>
</style>
修改 App.vue
修改 App.vue 文件,移除 HelloWorld 组件,使用 JdGoods2 组件,内容如下:
<template>
<!-- 模板 -->
<div id="app">
<JdGoods2 v-for="(item,index) in goods" :key="index" v-bind:gname="item.name" :price="item.price" :img="item.img" img_width="200"></JdGoods2>
</div>
</template>
<script>
//导入 JdGoods 组件
import JdGoods2 from './components/JdGoods2.vue'
export default {
name: 'App',
components: {
JdGoods2 //注册局部组件
},
data:function(){
return {
goods:[
{
name:"小天鹅洗衣机",
price:2000,
img:"img/20231116_133706.png",
},
{
name:"逻辑",
price:5000,
img:"img/iphone.jpg",
},
{
name:"蝰蛇",
price:3000,
img:"img/mouse.jpg",
},
]
}
}
}
</script>
启动服务
npm run serve
访问
打开浏览器访问:http://localhost:8080/