组件通信常用方法
以下demo github地址: feature/communication分支
- props
<!-- Child.vue -->
<template>
<div>
<p>{{msg}}</p>
</div>
</template>
<script>
export default {
// props: ['msg'], //基本用法
props: {
msg: {
type: String,
//required: true, // 默认false,是否必传 必传自然就没有default
default: ""
}
}
}
</script>
<!-- Parent.vue -->
<template>
<Child msg='from parent to child message'></Child>
</template>
<script>
import Child from './Child.vue'
export default {
components: {
Child
}
}
</script>
- $emit / $on ( 发布/订阅)
<!-- Child.vue -->
<template>
<div>
<p>Child1.vue</p>
<input type="text" v-model="val" @input="handleInput">
</div>
</template>
<script>
export default {
data() {
return {
val : ""
}
},
mounted() {
this.handleInput();
},
methods : {
handleInput () {
this.$emit('emitEvent', this.val)
}
}
}
</script>
<!-- Parent.vue -->
<template>
<div>
<Child @emitEvent="getFromChild"></Child>
<p>从child订阅的值:{{val}}</p>
</div>
</template>
<script>
import Child from './Child.vue'
export default {
components: {
Child
},
data() {
return {
val : "",
}
},
methods: {
getFromChild(args){
this.val = args;
}
}
}
</script>
- event bus (总线 --> $emit / $on)
//main.js
Vue.prototype.$bus = new Vue(); //注册全局的bus
//Bus.vue
<template>
<div>
<Bus1></Bus1>
<Bus2></Bus2>
</div>
</template>
<script>
import Bus1 from "../components/module/Bus1";
import Bus2 from "../components/module/Bus2";
export default {
components: {
Bus1,
Bus2
}
};
</script>
//Bus1.vue
<template>
<div>
<p>Bus1</p>
<input type="text" v-model="inputVal" />
<button @click="handleAddBusVal">Bus1发布</button>
</div>
</template>
<script>
export default {
mounted(){
this.$nextTick(()=>{
this.handleAddBusVal();
})
},
data() {
return {
inputVal: 'Event Bus1 message to Bus2'
}
},
methods: {
handleAddBusVal() {
this.$bus.$emit('addBusVal',this.inputVal);
}
},
};
</script>
// Bus2.vue
<template>
<div>
<p>Bus2</p>
<p>{{busVal}}</p>
</div>
</template>
<script>
export default {
data() {
return {
busVal: '2222'
};
},
mounted() {
this.$bus.$on('addBusVal',target=>{
this.busVal = target
});
}
};
</script>
- VueX
VueX官方文档
网友评论