创建父组件(上)
<!-- parent.vue -->
<template>
<div>
<h1>我是父组件</h1>
<hr>
<!-- 这里要调用子组件 -->
</div>
</template>
创建子组件(下)
<!---- child.vue --->
<template>
<div>
<h2>我是子组件</h2>
</div>
</template>
把子组件引入到父组件并且注册使用
<!-- parent.vue -->
<template>
<div>
<h1>我是父组件</h1>
<hr>
<!-- 这里要调用子组件 -->
<child />
</div>
</template>
<script>
// 第一步:导入组件
import Child from './child'
export default {
// 第二步:注册组件
components: {
Child
}
}
</script>
在父组件里面定义一个数据并且进行数据的传递
<!-- parent.vue -->
<template>
<div>
<h1>我是父组件</h1>
<hr>
<!-- 这里要调用子组件 -->
<child :title="msg" />
</div>
</template>
<script>
// 第一步:导入组件
import Child from './child'
export default {
// 第二步:注册组件
components: {
Child
},
data() {
return {
msg: '我是父组件的数据'
}
},
}
</script>
在子组件中通过props接收
<template>
<div>
<h2>我是子组件</h2>
<!-- 这里放的是父组件传递过来的数据 -->
<p>{{ title }}</p>
</div>
</template>
<script>
export default {
props: ['title']
}
</script>