1、在父组件app.vue的scripts下引入子组件HelloWorld.vue,例如
import HelloWorld from './components/HelloWorld'
2、添加到components中,
components:{
HelloWorld
}
3、在父组件的template下渲染子组件的内容,
<HelloWorld />
4、父组件向子组件传递数据,代码如下,在中,text是向子组件传递的属性名,message是父组件向子组件传递的数据,其中:不能缺少,表示动态传递数据,
<template>
<div id="app">
<img src="./assets/logo.png">
<HelloWorld :text = message />
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld'
export default {
name: 'App',
components:{
HelloWorld
},
data(){
return {
message:'你好,Vue!'
}
}
}
</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>
5、子组件接收数据,并渲染页面,代码如下,其中props是用来接收父组件传递的字符串数据‘你好,Vue!’,其中text对应父组件中传递来的属性名,其中数据类型为String,默认为空字符串,
<template>
<p>{{text}}</p>
</template>
<script>
export default {
name: 'HelloWorld',
props:{
text:{
type:String,
default: ''
}
}
}
</script>