随笔都是学习笔记
随笔仅供参考,为避免笔记中可能出现的错误误导他人,请勿转载。

创建一个自定义组件:

<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 2022-11-14 13:59  时间完全不够用啊  阅读(55)  评论(0编辑  收藏  举报