Vue 常用的三种传值方式
1.父传子
2.子传父
3.兄弟组件传值
父传子
父组件的内容传递给子组件其实很简单
首先建立俩个Vue的组件,
<template>
<div>
<span>父组件:</span>
</div>
</template>
我们的template下,只能拥有一个标签
<template>
<div>
<span>子组件:</span>
</div>
</template>
我们把子组件的内容引入到父组件里
import child from './child.vue' // 引入子组件
然后,我们开始注册自定义标签
export default {
name: "father",
components:{
child //这个名字是上面我们引进来的child.vue,俩个名字需相同
}
}
<template>
<div>
<span>父组件:</span>
<child></child>
</div>
</template>
我们开始v-model绑定数据
在data数据里写上name
export default {
name: "father",
data() {
return {
name: ''
}
},
components:{
child //这个名字是上面我们引进来的child.vue,俩个名字需相同
}
}
我们在组件中绑定data数据的name,在自定义标签中传递要传递的值
<template>
<div>
<span>父组件:</span>
<input type="text" v-model="name">
<child :notice="name"></child>
</div>
</template>
最后,在child.vue组件中利用props来接收传递来的参数
export default {
name: "child",
data() {
return {}
},
props: ['notice']
}
在上面的模板中运用传递来的参数
<template>
<div>
<span>子组件:{{notice}}</span>
</div>
</template>
子传父
首先,我们要点击一个按钮,使子组件的值传到父组件。
于是,我们在子组件,写点击事件。
<template>
<div>
<span>子组件:</span>
<input type="text" v-model="childvalue"> //双向绑定childvalue
<input type="button" value="传值到父亲" @click="childclick"> //点击事件
</div>
</template>
export default {
name: "child",
props: ['notice'], //接收父组件传递的值
data() {
return {
childvalue:this.notice
}
},
methods: {
childclick() {
this.$emit("childByvalue", this.childvalue) // 利用$emit的方法把值传递给父组件
}
}
}
我们在父组件中接收传递的值利用的是@
<child :notice="name" @childByvalue="childByvalue"></child>
在下面的methods写方法
methods : {
childByvalue (val) {
this.name=val
}
},
这时候就用到了watch来监听了。
在父组件中监听传递过了的值。
watch:{
notice () {
this.childvalue=this.notice
}
},
这样父子组件的通信就完成了。
兄弟组件传参
兄弟组件传参,需要有共同的父组件。需要定义公共的公共实例文件,作为中间仓库。不然达不到传值效果。
创建bus.js做为公共的仓库文件
bus.js内容为
import Vue from 'Vue'
export default new Vue
创建child1.vue,child2.vue
child1.vue内容为
<template>
<div>
<span>child1</span>
<span>{{msg}}</span>
<button @click="childclick">点击</button>
</div>
</template>
<script>
import bus from './bus.js'
export default {
name: "child1",
data () {
return {
msg :'123'
}
},
methods : {
childclick () {
bus.$emit('val',this.msg)
}
}
}
</script>
<style scoped>
</style>
child2的内容为
<template>
<div>
<span>child2</span>
<span>{{cmsg}}</span>
</div>
</template>
<script>
import bus from './bus.js'
export default {
name: "child2",
data () {
return {
cmsg : ''
}
},
mounted () {
let that =this
bus.$on('val',(data)=>{
console.log(data);
this.cmsg=data
})
}
}
</script>
<style scoped>
</style>
在父组件中导入注册
import child1 from './child1.vue'
import child2 from './child2.vue'
components:{
child1,
child2
}