Vue学习组件间传值笔记
1、父组件向子组件传值:
使用props来向子组件传值
父组件代码:
<template>
<div class="home">
<home-icons :list="iconsList"></home-icons>
</div>
</template>
<script>
import HomeIcons from './components/icons'
export default {
data () {
return {
bannerList: [{
id: "0001",
imgUrl: "http://img1.qunarzz.com/piao/fusion/1801/1a/94428c6dea109402.jpg_640x200_2cf590d8.jpg"
}]
}
},
components: {
HomeIcons
}
}
</script>
Icons子组件代码:
<template>
<div class="icons">
<div class="icon-img">
<img :src="item.imgUrl">
</div>
<div class="icon-name">{{item.desc}}</div>
</div>
</div>
</template>
<script>
export default {
props: {
list: Array
}
}
</script>
2、子组件向父组件传值
通过绑定事件及使用$emit
父组件中的代码:
<template>
<div class="parent">
<h2>{{ message}}</h2>
<p>父组件接手到的内容:{{ username }}</p>
<child psMsg="父传子的内容" @pull="getUser"></child> <!--绑定自定义事件pull-->
</div>
</template>
<script>
import child from './child'
export default {
name: 'parent',
data () {
return {
message: '父组件',
username:'',
}
},
components:{child},
methods:{
getUser(message){
this.username= message
}
}
}
</script>
子组件中的代码:
<template>
<div class="child">
<p>{{ childMessage }}</p>
<p>子组件接收到内容:{{ psMsg }}</p>
<input type="text" v-model="user" @change="setUser">
<button @click="setUser">传值</button>
</div>
</template>
<script>
export default {
name: "child",
data(){
return {
childMessage:'子组件',
user:'子传父的内容'
}
},
props:['psMsg'],
methods:{
setUser:function(){
this.$emit('pull',this.user)//将值绑定到pull上传递过去
}
}
}
</script>