背景
vue要进行数据交互,若父组件要向子组件传值要怎么办那
方法
父组件的标签引用时,添加v-bind,子组件的props接收注册
父组件App.vue
<template>
<div id="app">
<users v-bind:users="users"></users> //v-bind传值
</div>
</template>
<script>
import Users from './components/Users'
export default {
data(){
return {
users:[
{name:"beiqiu",position:"web开发",show:false},
{name:"beiqiu",position:"web开发",show:false},
{name:"beiqiu",position:"web开发",show:false},
{name:"beiqiu",position:"web开发",show:false},
{name:"beiqiu",position:"web开发",show:false},
{name:"beiqiu",position:"web开发",show:false},
{name:"beiqiu",position:"web开发",show:false},
{name:"beiqiu",position:"web开发",show:false},
{name:"beiqiu",position:"web开发",show:false}
]
}
},
components:{
"users":Users
}
}
</script>
<style scoped>
h1{
color:red;
}
</style>
子组件Users.vue
<template>
<div class="users">
<h1>hello users</h1>
<ul>
<li v-for="user in users" v-on:click="user.show=!user.show">
<h2>{{user.name}}</h2>
<h3 v-show="user.show">{{user.position}}</h3>
</li>
</ul>
</div>
</template>
<script>
export default{
name:"users", //props注册
// props:["users"], 这是简易方式
props:{ //这是官方方式
users:{
type:Array, //类型
required:true //是否规范
}
},
data(){
return{
}
}
}
</script>
<style scoped>
.users{
width:100%;
max-width:1200px;
margin:40px auto;
padding:0 20px;
box-sizing:border-box;
}
ul{
display:flex;
flex-wrap:wrap;
list-style-type:none;
padding:0px;;
}
li{
flex-grow:1;
flex-basis:200px;
text-align:center;
padding:25px;
border:1px solid #222;
margin:20px;
}
</style>
注意
传数组和列表都算是传“引用”,即子组件数据更改,父组件的数据也会更改,而传String字符串仅仅是传值,不会同步更改。