vue中传值方式
vue中传值方式一般有父传子、子传父、还有非父子之间的传递
父传子
导入子组件后,在子组件标签上自定义属性,然后再传需要的值
<template>
<div>
<son :fasong="name"></son>
</div>
</template>
<script>
// 父组件
import son from './child.vue'
export default {
name:'Father',
components:{
son
},
data(){
return{
name:'我是爸爸'
}
}
}
</script>
子组件通过props接收属性
<template>
<div>
<p>{{fasong}}</p>
</div>
</template>
<script>
// 子组件
export default {
name:'Chlid',
props:["fasong"],
}
</script>
输出结果:
子传父
<template>
<div>
<!-- 4.绑定子组件的自定义事件 -->
<son @aaa="jieshou"></son>
<p>[父组件中]{{arr}}</p>
</div>
</template>
<script>
// 父组件
//1.导入子组件,并插入template
import son from './child.vue'
export default {
name:'Father',
components:{ son },
data(){
return{
// 我这里定义了一个数组来接收
arr:[]
}
},
methods:{
jieshou(e){
// 5.接收子组件传来的参数到arr里
this.arr = e
}
}
}
</script>
<template>
<div>
<!--2. 定义一个事件 -->
<p @click="fasong">[子组件中]点击向父组件发送</p>
</div>
</template>
<script>
// 子组件
export default {
name:'Chlid',
data(){
return {
msg:'爸爸你好,我是儿子',
}
},
methods:{
fasong(){
//3. this.$emit(自定义属性,要传的参数)
this.$emit('aaa',this.msg)
}
},
}
</script>
输出结果:
非父子传值
先在入口文件添加EventBus
import Vue from 'vue'
import App from './App.vue'
//添加EventBus到Vue实例
Vue.prototype.$EventBus = new Vue
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
然后在父组件中导入两个子组件
<template>
<div id="app">
<son></son>
<son2></son2>
</div>
</template>
<script>
//父组件
import son from './components/child.vue'
import son2 from './components/child2.vue'
export default {
name: 'App',
components: {
son,son2
}
}
</script>
然后就可以实现兄弟之间的传值了
发送数据:
<template>
<div>
<p @click="fasong">[child]{{msg}}</p>
</div>
</template>
<script>
//子组件1
export default {
name:'Chlid',
data(){
return {
msg:'你好,我是child',
}
},
methods:{
fasong(){
// $emit 发送
this.$EventBus.$emit('hello',this.msg)
}
},
}
</script>
接收数据:
<template>
<div>
<p>[child2]收到,{{msg}}</p>
</div>
</template>
<script>
// 子组件2
export default {
name:'Chlid2',
data(){
return {
msg:'',
}
},
methods:{
jieshou(e){
this.msg = e
}
},
created(){
// $on() 接收
this.$EventBus.$on('hello',this.jieshou)
}
}
</script>
发送时绑定了一个点击事件,所以需要点击之后另一个兄弟组件才可以收到数据
结果:
点击前:
点击后: