1. 父向子组件传值
子组件 props接收
父组件
<template>
<div class="prent1">
父组件:
<br>
<br>
<!-- 引入子组件 -->
<chlid1 :inputName="name"></chlid1>
</div>
</template>
<script>
import chlid1 from './chlid1'
export default {
name:'prent1',
data () {
return {
name:'父向子组件传值了'
}
},
methods:{
},
components: {
chlid1,
},
}
</script>
子组件
<template>
<div class="chlid1">
子组件:
<span>{{inputName}}</span>
</div>
</template>
<script>
export default {
name:'chlid1',
data(){
return{
}
},
// 接受父组件的值
props: {
inputName: String,
required: true
},
methods:{
},
}
</script>
3. 子向父组件传值
$emit传
v-on:传的方法接收,
1.子组件
<template>
<div class="chlid">
子组件:
<!-- <span>{{inputName}}</span> -->
<button @click="ag_plablist">点我向父集传递数据</button>
</div>
</template>
<script>
export default {
name:'chlid',
data(){
return{
gavalue:'老头我爱你12121'
}
},
methods:{
ag_plablist(){
this.$emit('chlidfun',this.gavalue);
},
},
}
</script>
父组件
在这里插入代码片<template>
<div class="prent">
父组件:
<input type="text" v-model="name">
<br>
<br>
<!-- 引入子组件 -->
<!-- <child :inputName="name"></child> -->
<child v-on:chlidfun = "chlidfun"></child>
</div>
</template>
<script>
import child from './chlid'
export default {
name:'prent',
data () {
return {
name:''
}
},
methods:{
chlidfun(gavalue){
this.name = gavalue;
}
},
components: {
child,
},
}
</script>
5. 非父子组件传值
Bus.
e
m
i
t
传
,
B
u
s
.
emit传, Bus.
emit传,Bus.on收
首先创建一个bus.js
import Vue from 'vue'
export default new Vue()
组件1
通过点击向另一个组件传值
<template>
<div class="father">
<p>不是兄</p>
<input type="button" value="点击出发" @click="monClick">
<nofather></nofather>
</div>
</template>
<script>
import Bus from './js/bus'
import nofather from './nofather'
export default {
name:'father',
data(){
return{
agvalue:1 ,
}
},
methods:{
monClick(){
Bus.$emit('send',this.agvalue)
this.agvalue++;
},
},
components:{
nofather,
}
}
</script>
组件2
接收传过来的值
<template>
<div class="nofather">
<p>不是弟</p>
<span>{{name}}</span>
</div>
</template>
<script>
import Bus from './js/bus'
export default {
name:'nofather',
data(){
return{
name:''
}
},
methods:{
},
created(){
Bus.$on('send',(data) => {
this.name = data;
console.log(data)
})
}
}
</script>
如果有问题,可以加我微信一起讨论,我们一起进步!
屏幕前的你,加油!