版权声明:本文为博主原创文章,喜欢的话,可以通知我后进行转载哦! https://blog.csdn.net/maidu_xbd/article/details/89134193
在vue中,属性props用来实现将父组件的数据传递给子组件。当父组件的属性变化时,将传递给子组件。
引用:所有的 prop 都使得其父子 prop 之间形成了一个单向下行绑定:父级 prop 的更新会向下流动到子组件中,但是反过来则不行。这样会防止从子组件意外改变父级组件的状态,从而导致你的应用的数据流向难以理解。
以下通过示例展示:
两个子组件【PageOne.vue】【PageTwo.vue】分别通过属性props访问父组件【App.vue】的数据。
在【App.vue】中,导入子组件并在template中渲染,并绑定data中的数据。
绑定数据:【v-bind:informations="informations"】
<template>
<div id="app">
<page-one v-bind:informations="informations"></page-one>
<page-two v-bind:informations="informations"></page-two>
</div>
</template>
<script>
import PageOne from "./components/PageOne";
import PageTwo from "./components/PageTwo";
export default {
name: "App",
data() {
return {
informations: [
{ name: "Lucy", age: 18 },
{ name: "Mike", age: 19 },
{ name: "Stanfen", age: 22 },
{ name: "Alice", age: 30 }
]
};
},
components: {
"page-one": PageOne,
"page-two": PageTwo
}
};
</script>
在子组件【PageOne.vue】【PageTwo.vue】中通过属性【props】传递父组件的数据:【props: ["informations"]】
<template>
<div class="page-one">
<h3>组件1【props】属性传值- 调用父组件数据</h3>
<ul>
<li v-for="info in informations" :key="info">
<span>{{info.name}}</span>
<span>{{info.age}}</span>
</li>
</ul>
</div>
</template>
<script>
export default {
name: "page-one",
props: ["informations"],
data() {
return {};
}
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.page-one {
background: rgba(236, 236, 115, 0.788);
width: 600px;
margin: 10px auto;
}
ul li {
line-height: 30px;
}
</style>