父传子
props传参
<template>
<div id="app">
<Child :inp="inp" />
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
inp:'父传子'
}
},
components:{
Child:{
props:['inp'],
template: `<div>
{{inp}}
</div>`,
}
}
}
</script>
子传父
方法一 props传回掉函数
<template>
<div id="app">
<Child :inp="inp" @updateInp="update" />
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
inp:'父传子'
}
},
methods: {
update(options){
console.log(options)
}
},
components:{ //子组件
Child:{
props:['inp'],
template: `<div>
{{inp}}
<button type='button' @click="changeValue">修改</button>
</div>`,
methods: {
changeValue(){
this.$emit('updateInp','子传父');
}
},
}
}
}
</script>
方法二 v-bind的sync
<template>
<div id="app">
<Child :inp.sync="inp" />
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
inp:'父传子'
}
},
updated() {
console.log(this.inp)
},
components:{ //子组件
Child:{
props:['inp'],
template: `<div>
{{inp}}
<button type='button' @click="changeValue">修改</button>
</div>`,
methods: {
changeValue(){
this.$emit('update:inp','子传父');
}
},
}
}
}
</script>
方法三 ref
<template>
<div id="app">
<Child ref="child" :inp="inp" />
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
inp:'父传子'
}
},
mounted(){
this.$refs.child.$on('updateInp',options=>{
console.log(options)
})
},
components:{ //子组件
Child:{
props:['inp'],
template: `<div>
{{inp}}
<button type='button' @click="changeValue">修改</button>
</div>`,
methods: {
changeValue(){
this.$emit('updateInp','子传父');
}
},
}
}
}
跨组件传参
Vue本身也有 o n 、 on、 on、emit,在main.js挂载一个 Vue.prototype. b u s = n e w V u e ( ) ; 也 可 以 。 但 是 用 俩 个 方 法 就 实 例 一 个 V u e 这 样 肯 定 没 有 自 行 封 装 一 个 bus = new Vue(); 也可以。但是用俩个方法就实例一个Vue这样肯定没有自行封装一个 bus=newVue();也可以。但是用俩个方法就实例一个Vue这样肯定没有自行封装一个bus好。
封装$bus
class Bus{
constructor() {
this.events = {};
}
$emit(eventName, params){
this.events[eventName].forEach(item => {
item(params)
});
}
$on(eventName, ck){
if(this.events[eventName]){
this.events[eventName].push(ck)
}else{
this.events[eventName] = [ck]
}
}
}
export default Bus
// import Bus from '../utils/Bus'; //在main.js引入
// Vue.prototype.$bus = new Bus(); //挂载到Vue的prototype上
//用法
// this.$bus.$on('undataValue',(options)=>{console.log(options)}) //父
// this.$bus.$emit('undataValue','子传父'); //子
用法案例
<template>
<div id="app">
<Child :value='inp' />
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
inp:'父传子'
}
},
created() {
console.log(this)
this.$bus.$on('undataValue',(options)=>{
console.log(options)
this.inp = options;
})
},
components:{ //子组件
Child:{
props:['value'],
template: `<div>
{{value}}
<button type='button' @click="changeValue">修改</button>
</div>`,
methods: {
changeValue(){
this.$bus.$emit('undataValue','子传父');
}
},
}
}
}
</script>