vue组件父子页面相互传值及调用方法
前言
开发过程中经常会碰到多个页面重复使用一个页面的问题可以通过vue的组件来实现这个功能,这里记录一下我使用vue组件的过程。
代码
父页面parent.vue向子页面传值或调用子页面child.vue的方法
parent.vue
<div>
<myChild v-bind:msg="msg" ref="myChild"></myChild>
<button @click="toChild">调用子组件方法</button>
</div>
<script>
//引入子页面
import myChild from "/child.vue";
export default {
components:{
myChild
},
data(){
return {
msg : "123"
}
},
methods : {
toChild(){
this.$refs.myChild.dataForParent();
}
}
}
</script>
child.vue
<template>
<div>{{msg}}</div>
</template>
<script>
export default {
props : ["msg"],
methods : {
dataForParent(){
console.log("父组件已经调用");
}
}
}
</script>
页面引入子组件之后写在components里面多个可以用逗号隔开,我这里子组件的别名是myChild,所以调用子组件的标签也叫<myChild></myChild>,这个标签也可以写成<my-child></my-child>看你们想要什么样的风格。
向子组件传值需要在子组件上通过v-bind绑定需要传的值我这里写的是v-bind:msg="msg"。可以写多个也可以把参数封装成对象传过去,子组件接收参数写在props : ["msg"]里,多个用逗号隔开。
页面中直接展示用{{msg}}展示,在方法中可以用this.msg获取接收的参数。如果是对象{{msg.xxx}}
调用子组件的方法需要在子组件的标签上写上ref,我这里写的是ref="myChild",调用方法语句
this.$refs.myChild.dataToParent();
子组件调用父页面的方法
parent.vue
<template>
<div>
<myChild @dataForChild="dataForChild" v-bind:msg="msg" ref="myChild"></myChild>
<button @click="toChild">调用子组件方法</button>
</div>
</template>
<script>
//引入子页面
import myChild from "/child.vue";
export default {
components:{
myChild
},
data(){
return {
msg : "123"
}
},
methods : {
toChild(){
this.$refs.myChild.dataToParent();
},
dataForChild(val){
console.log("子组件传来:"+val);
}
}
}
</script>
child.vue
<template>
<div>{{msg}}</div>
<button @click="sendParent"></button>
</template>
<script>
export default {
props : ["msg"],
methods : {
dataToParent(){
console.log("父组件已经调用");
},
sendParent(){
this.$emit("dataForChild","aaa");
}
}
}
</script>
父页面需要在子组件的标签上通过@方法名来监听,我这里写的是@dataForChild="dataForChild",子页面中调用父页面的方法通过
this.$emit("父页面子组件上通过@监听的方法名称","参数");语句调用,我这里写的是
this.$emit("dataForChild","aaa");
如果想刷新子组件需要在父页面子组件的标签上使用v-if="xxx",使用语句
this.xxx= false;
this.$nextTick(() =>{
this.xxx = true;
})
来刷新组件。