随笔都是学习笔记
随笔仅供参考,为避免笔记中可能出现的错误误导他人,请勿转载。
posts - 398,comments - 0,views - 13万

创建一个自定义组件:

复制代码
<template>
    <h1>Here is ComponentForOne!!</h1>
    <p>{{title}}</p>
    <p>age = {{age}}</p>
    <ul style="background-color:aqua">
        <li v-for="(item,index) in arr" :key="index">{{item}}</li>
    </ul>
</template>

<script>
// 导出
export default{
// 当前组件的名称,在导入使用时需要用到
name:"ComponentForOne",
// 通过props在组件间传递参数
props:{
    title:{
        type:String,
        default:""
    },
    age:{
        type:Number,
        default:20
    },
    arr:{
        type:Array,
        // 数组和对象必须使用函数返回
        default:function(){
            return []
        }
    }
}
}
</script>
<!-- scoped :如果添加了此属性,表示只在当前组件中生效 -->
<style scoped>
h1{
    color: aqua;
}
</style>
复制代码

在App.vu中引入:

复制代码
<template>
  <img alt="Vue logo" src="./assets/logo.png">
  <!-- 下面使用组件:组件标签名 -->
  <ComponentForOne :title="msg" :age="age" :arr="arr"/>
</template>

<script>
// 此处引入组件 import 组件标签名 from 组件所在位置 
import ComponentForOne from './components/ComponentForOne.vue';

export default {
  name: 'App',
  components: {
    // 挂载组件
    ComponentForOne
  },
  data(){
    return{
      msg:"App中的msg",
      age:12,
      arr:["1","2","3"]
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
复制代码

在App.vue中通过将值绑定在属性上进行传递,在自定义组件中通过 props 进行接收然后设置到标签中。

对应关系:

  App.vue中的 data 中设置值,App.vue 的自定义组件标签中设置属性,并将值设置为属性值,

  自定义组件中的 props 引入App.vue 中设置的值,然后设置到标签中。

posted on   时间完全不够用啊  阅读(74)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示