vue组件的方法调用
方案一:通过ref直接调用子组件的方法;//父组件中<template><div><Button @click="handleClick">点击调用子组件方法</Button><Child ref="child"/></div></template><script>import Child from '
·
方案一:通过ref直接调用子组件的方法;
//父组件中
<template>
<div>
<div @click="handleClick">点击调用子组件方法</div>
<Child ref="child"/>
</div>
</template>
<script>
import Child from './child';
export default {
methods: {
handleClick() {
this.$refs.child.sing();
},
},
components: {
Child
}
}
</script>
//子组件中
<template>
<div>我是子组件</div>
</template>
<script>
export default {
methods: {
sing() {
console.log('我是子组件的方法');
},
},
};
</script>
方案二:通过组件的 e m i t 、 emit、 emit、on方法;
//父组件中
<template>
<div>
<div @click="handleClick">点击调用子组件方法</div>
<Child ref="child"/>
</div>
</template>
<script>
import Child from './child';
export default {
components: {
Child
}
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>
直接在子组件中通过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>
<div @click="childMethod()">点击</div>
</div>
</template>
<script>
export default {
methods: {
childMethod() {
this.$parent.fatherMethod();
}
}
};
</script>
在子组件里用$emit向父组件触发一个事件,父组件监听这个事件就行了。
//父组件
<template>
<div>
<child @fatherMethod="fatherMethod"></child>
</div>
</template>
<script>
import child from '~/components/dam/child';
export default {
components: {
child
},
methods: {
fatherMethod() {
console.log('测试');
}
}
};
</script>
//子组件
<template>
<div>
<div @click="childMethod()">点击</div>
</div>
</template>
<script>
export default {
methods: {
childMethod() {
this.$emit('fatherMethod');
}
}
};
</script>
父组件把方法传入子组件中,在子组件里直接调用这个方法
//父组件
<template>
<div>
<child :fatherMethod="fatherMethod"></child>
</div>
</template>
<script>
import child from '~/components/dam/child';
export default {
components: {
child
},
methods: {
fatherMethod() {
console.log('测试');
}
}
};
</script>
//子组件
<template>
<div>
<div @click="childMethod()">点击</div>
</div>
</template>
<script>
export default {
props: {
fatherMethod: {
type: Function,
default: null
}
},
methods: {
childMethod() {
if (this.fatherMethod) {
this.fatherMethod();
}
}
}
};
</script>
//子组件更简单的方法
<template>
<div>
<div @click="fatherMethod()">点击</div>
</div>
</template>
<script>
export default {
props: {
fatherMethod: {
type: Function,
default: null
}
},
methods: {
}
};
</script>
更多推荐
已为社区贡献2条内容
所有评论(0)