<!-- 父组件 -->
<template>
<div>
<child @fatherMethod="fatherbtn"></child>
</div>
</template>
<script>
import child from '~/components/dam/child';
export default {
components: {
child
},
methods: {
fatherbtn (msg) {
console.log('测试',msg);//我是子组件的msg
}
}
};
</script>
子组件通过this.$emit()的方式将值传递给父组件
注意:这里的func是父组件中绑定的函数名
父组件:
<!-- 子组件 -->
<template>
<div>
<button @click="childMethod()">点击</button>
</div>
</template>
<script>
export default {
data () {
return {
//将msg传递给父组件
msg: "我是子组件的msg",
}
},
methods: {
childMethod () {
//fatherMethod: 是父组件指定的传数据绑定的函数,this.msg:子组件给父组件传递的数剧
this.$emit('fatherMethod',this.msg);
}
}
};
</script>
父组件向子组件传值
父组件:
<template>
<div>
父组件:
<input type="text" v-model="name">
<br>
<br>
<!-- 引入子组件 -->
<child :inputName="name"></child>
</div>
</template>
<script>
import child from './child'
export default {
components: {
child
},
data () {
return {
name: ''
}
}
}
</script>
子组件
<template>
<div>
子组件:
<span>{{inputName}}</span>
</div>
</template>
<script>
export default {
// 接收父组件的值
props: {
inputName: String,
required: true
}
}
</script>
直接在子组件中通过this.$parent.event来调用父组件的方法
<!-- 父组件 -->
<template>
<div>
<child></child>
</div>
</template>
<script>
import child from '~/components/dam/child';
export default {
components: {
child
},
methods: {
fatherMethod () {
console.log('测试');
}
}
};
</script>
<!-- 子组件 -->
<template>
<div>
<button @click="childMethod()">点击</button>
</div>
</template>
<script>
export default {
methods: {
childMethod() {
this.$parent.fatherMethod();
}
}
};
</script>
Vue项目中如何在父组件中直接调用子组件的方法:
方案一:通过ref直接调用子组件的方法;
//父组件中
<template>
<div>
<Button @click="handleClick">点击调用子组件方法</Button>
<Child ref="child"/>
</div>
</template>
<script>
import Child from './child';
export default {
methods: {
handleClick() {
this.$refs.child.sing();
},
},
}
</script>
//子组件中
<template>
<div>我是子组件</div>
</template>
<script>
export default {
methods: {
sing() {
console.log('我是子组件的方法');
},
},
};
</script>
二、通过组件的$emit、$on方法;
//父组件中
<template>
<div>
<Button @click="handleClick">点击调用子组件方法</Button>
<Child ref="child"/>
</div>
</template>
<script>
import Child from './child';
export default {
methods: {
handleClick() {
this.$refs.child.$emit("childmethod") //子组件$on中的名字
},
},
}
</script>
//子组件中
<template>
<div>我是子组件</div>
</template>
<script>
export default {
mounted() {
this.$nextTick(function() {
this.$on('childmethods', function() {
console.log('我是子组件方法');
});
});
},
};
</script>
感觉还可以点个赞再走·····