vue单项数据流
父传子单项数据流
vue的单向数据流:
- 父组件的更新会触发子组件的更新,但子组件的更新不会触发父组件的更新,只能是父到子,父组件可以把信息传给子组件,但是子组件不能传给父组件
如果想修改子组件的data:
- 1.把接受到的属性值复制给data,不改属性,改子组件的data
- 2.把prop以计算属性定义
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
<title>Document</title>
<style>
.container {
box-sizing: border-box;
margin: 20px auto;
padding: 0 10px;
border: 1px solid #AAA;
width: 300px;
}
.container h3 {
font-size: 16px;
line-height: 40px;
border-bottom: 1px dashed #AAA;
font-weight: bold;
}
.red {
color: red !important;
}
</style>
</head>
<body>
<!-- 局部组件实践和组件之间的嵌套:
选择父组件的时候,到了子组件,先渲染子组件,然后再渲染父组件
-->
<div id="app">
<my-vote v-for="item in voteList" :title="item.title" ></my-vote>
</div>
<template id="MyVoteTemplate">
<div class="container">
<h3><span v-text='title'> </span>(<span>0</span>)</h3>
<vote-content></vote-content>
<vote-button></vote-button>
</div>
</template>
<template id="VoteContentTemplate">
<div class="content">
<p>支持人数:<span>0</span> </p>
<p>反对人数:<span>0</span> </p>
<p>支持率:<span>0%</span> </p>
</div>
</template>
<template id="VoteButtonTemplate">
<div class="footer">
<button type="button" class="btn btn-primary">支持</button>
<button type="button" class="btn btn-danger">反对</button>
</div>
</template>
<script src="../node_modules/vue/dist/vue.min.js"></script>
<script>
//=>注册组件
//=>在组件中调取渲染使用
// 父组件->子组件的渲染是从外向内预准备渲染,子组件是从内向外先渲染,
/*vue的单向数据流:
父组件的更新会触发子组件的更新,但子组件的更新不会触发父组件的更新,只能是父到子,父组件可以把信息传给子组件,但是子组件不能传给父组件
如果想修改子组件的data:
1.把接受到的属性值复制给data,不改属性,改子组件的data
2.把prop以计算属性定义
*/
const VoteContent = {
template: '#VoteContentTemplate',
data() {
return {
}
}
};
const VoteButton = {
template: '#VoteButtonTemplate',
data() {
return {
}
}
};
const MyVote = {
template: '#MyVoteTemplate',
props: ["title"],
data() {
return {}
},
components: {
VoteContent,
VoteButton
},
mounted() {
//=>基于属性传递的值,只能获取使用,不能在子组件中修改,(修改后会有效果,子组件会重现渲染,但是控制台报错)
// this.title = 'AAA';
setTimeout(() => {
this.voteList = this.voteList.map(item => {
if (item.id === 1 ){
item.title='前端好难呀!奥'
}
return item;
});
},1000)
}
};
let vm = new Vue({
el: '#app',
data: {
voteList: [{
id: 1,
title: '前端细化'
}, {
id: 2,
title: '人工智能'
}
]
},
components: {
MyVote
}
})
</script>
</body>
</html>