vue的父组件与子组件实现数据通信的5种方式
一、父=>子
父:
<div>
<child :child-str="data"></child>
</div>
import child from './school-child';
export default {
name: "parent",
components:{child},
data(){
return {
data:'我要向子组件传递数据'
}
},
}
子:(子组件通过props来接受数据)
<div>我是子组件,接收父组件传递过来的值-{{childStr}}</div>
export default {
name: "child",
props:{
childStr:{
type:String,
default:'我是空的'//如果不传值,显示的值
}
}
}
二、子=>父(通过触发事件来改变组件的数据)
子:
<el-button @click="clickMe" type="primary">点击我传值</el-button>
methods:{
clickMe(){
this.$emit('clickStr','传递的值')
}
}
父
<child @clickStr="showChild"></child>
methods:{
showChild(msg){
console.log(msg);
}
}
三、兄弟之间通信(二者无关系)
兄弟1 => 兄弟2 通信,需要公共实例来做为桥梁
bus.js
import Vue from 'vue'
export default new Vue();
兄弟一
import Bus from '../../config/bus'
Bus.$emit('xiongdi','兄弟')
兄弟二
import Bus from '../../config/bus'
Bus.$on('xiongdi',(arg) => {
console.log(arg);
})
其他:VueX , provide / inject API, dispatch / broadcast 和 findComponents等。。。。
四、父子组件之间-可能需要对一个 prop 进行“双向绑定”,见官网
子组件传递
this.$emit('update:value',location);
父组件接收
{{doc}}
<child v-bind:value.sync="doc"/>
五、利用v-model实现通信:官网链接
目标:父组件、子组件按钮改变同一个内容showFlag,实现效果
父组件code
<template>
<div>
<h1>这是组件外面的内容:{{showFlag}}</h1>
<button @click="showClick">父组件按钮</button>
<test-child v-model="showFlag" ></test-child>
</div>
</template>
<script>
import testChild from './test-child'
export default {
name:'parent',
components:{
testChild
},
data(){
return{
showFlag:true
}
},
methods:{
showClick(){
this.showFlag = !this.showFlag;
}
}
}
</script>
<style lang="scss" scoped></style>
子组件 code
<template>
<div>
<div class="hello">
<h1>这是子组件里面的内容 {{checked}}</h1>
<button @click="close">子组件按钮</button>
</div>
</div>
</template>
<script>
export default {
name: 'test-child',
model: {
prop: 'checked',
event: 'change'
},
props: {
checked: {
type: Boolean
}
},
methods: {
close() {
this.$emit('change', !this.checked);
}
}
};
</script>
<style scoped>
</style>