父组件传递数据给子组件用props,父组件中使用子组件,子组件用props接收父组件数据。
Home父组件代码:
<template> <div> {{test}} <!-- 使用子组件,绑定父组件数据数据 --> <Child :test="test"></Child> </div> </template> <script> // import子组件 import Child from './Child.vue' export default { name: "Home", //components引入子组件 components:{ Child }, data () { return { test:123 }; } } </script> <style lang="css" scoped> </style>
Child子组件代码:
<template>
<div>
<!-- 使用子组件数据 -->
{{test}}
</div>
</template>
<script>
export default {
name: "Child",
// props使用获取父组件数据
props:["test"],
data () {
return {
};
},
created(){
// 使用子组件数据
console.log(this.test);
}
}
</script>
<style lang="css" scoped>
</style>