1、子组件:DemoHello.vue文件
<template>
<div class="demo">
<h1>测试创建组件</h1>
<p>{{msg}}</p>
<p>年龄:{{age}}</p>
<p>总数:{{count}}</p>
<p>内容:{{name}}</p>
</div>
</template>
<script>
export default {
//组件名称,必须多个单词,不能单个单词
name: 'DemoHello',
//获取父级组件传递过来的参数信息,可以定义传递过来的参数的类型。
props: {
msg: String,
age:Number,
count:Number,
// 对name参数进行更加详细的校验,类型为字符串,必填
name:{
type: String,
required: true
}
},
// 获取父级组件传递过来的参数信息,这种写法就是不定义传递过来的参数类型
// props:["msg","age","count","name"],
}
</script>
<style scoped>
.demo{
color: red;
}
</style>
注意:其中 props里面参数的类型有:String、Number、Boolean、Array、Object、Function、Promise等,详情看:Prop — Vue.js
2、父组件:App.vue文件
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<!-- 在父组件中使用组件 -->
<DemoHello msg="父级组件给子级组件传递国定参数" age="36啊" :count="count" :name="name"/>
</div>
</template>
<script>
import DemoHello from './components/DemoHello.vue';
export default {
name: 'App',
//组件中的data不能是对象,只能是函数,这个函数返回的是对象
data: function () {
return {
count: 999,
name:"动态数据:从父组件传递给子组件动态数据"
}
},
//组件注册,必须要在data函数后面,不让data函数里面的值不会加载到这个组件中去。
components: {
DemoHello
},
}
</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>
注意: 这里从父组件传递给子组件的值,可以是具体的数据,也可以是 methods 中的函数,传递函数的格式和传递具体的数据的格式是一样的。
父组件的方法传递给子组件后,子组件可以通过this直接调用。
https://cn.vuejs.org/v2/guide/components-props.html#%E7%B1%BB%E5%9E%8B%E6%A3%80%E6%9F%A5
更多的组件之间传值方式:vue获取兄弟组件的值2020_vue 组件通信_葱 葱葱葱葱的博客-CSDN博客