传值:string number boolean
传引用:array object
注意:传引用就类似与C的传值和传址 比如传递个array 然后删除一个元素其他地方调用array的也会被删除
例子:
app.vue
<template>
<div id="app">
<app-header v-bind:title="title"></app-header>
<!--通过父组件传值需要找到两个的契合点然后给个属性绑定上去-->
<!--然后在子组件中调用父组件中的值-->
<users v-bind:users="users"></users>
<users v-bind:users="users"></users>
<app-footer v-bind:title="title"></app-footer>
</div>
</template>
<script>
//局部注册组件
import Users from './components/Users'
import Header from './components/Header'
import Footer from './components/Footer'
export default {
name: 'app',
data(){
return{
//title:"这是第一个Vue脚手架"
users:[
{name:"Henry",position:"Web开发",show:false},
{name:"Henry",position:"Web开发",show:false},
{name:"Henry",position:"Web开发",show:false},
{name:"Henry",position:"Web开发",show:false},
{name:"Henry",position:"Web开发",show:false},
{name:"Henry",position:"Web开发",show:false},
{name:"Henry",position:"Web开发",show:false},
],
title:"传递的是一个值,(number string boolean)"
}
},
components:{
//也可以省略掉key
//Users
"users":Users,
//不能直接使用header作为Key因为会和组件里面的原生代码冲突
"app-header":Header,
"app-footer":Footer
}
}
</script>
<style scoped>
h1{
color: purple;
}
</style>
Header.vue
<template>
<header v-on:click="changeTitle">
<h1>{{title1}}{{title}}</h1>
</header>
</template>
<script>
export default {
name: 'app-header',
props: {
title:{
type:String
}
},
data(){
return{
title1:"Vue.js Demo"
}
},
methods:{
changeTitle:function () {
this.title="changed";
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
header{
background: lightgreen;
padding: 10px;
}
h1{
color: #222;
text-align: center;
}
</style>
Users.vue
<template>
<div class="users">
<h1>Hello Users</h1>
<ul>
<li v-for="(user,index) in users" :key="index"
v-on:click="user.show=!user.show">
<h2>{{user.name}}</h2>
<h2 v-show="user.show">{{user.position}}</h2>
</li>
</ul>
<button v-on:click="deleteUser">删除</button>
</div>
</template>
<script>
export default {
name: 'users',
// 拿去父组件中的值用props
//这种也可以拿到但是不严谨
// props:["users"],
props:{
//最好的方法就是给它指定个对象和属性
users:{
//需要告诉它当前users里面传的值是什么
type:Array,
//并且它请求的时候它这里面是不是规格的Array
required:true
}
},
data(){
return{
}
},
methods:{
deleteUser:function () {
this.users.pop();
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<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: 0;
}
li{
flex-grow: 1;
flex-basis: 200px;
text-align: center;
padding: 30px;
border: 1px solid #222;
margin: 10px;
}
</style>
Footer.vue
<template>
<footer>
<p>{{copyright}} {{title}}</p>
</footer>
</template>
<script>
export default {
name: 'app-footer',
props: {
title:{
type:String
}
},
data(){
return{
copyright:"Copyright 2019 Vue Demo"
}
}
}
</script>
<style scoped>
footer{
background: #222;
padding: 6px;
}
p{
color: lightgreen;
text-align: center;
}
</style>