已经很久没有写博客了,这两天又学习了几招
组件化是VUE最大的一个特点,但是有个东西竟然一点都不知道,那就太lipu了,下面就看一下吧
父组件获取子组件的方法
法一:
父组件中
<template>
<div class="father">
<div class="father_box" @click="getSon">This is Father</div>
<son ref="son"></son>
</div>
</template>
<script>
import son from "@/components/son";
export default {
components: {
son,
},
methods: {
getSon() {
this.$refs.son.getFather();
},
},
};
</script>
子组件中
<template>
<div class="son">
<div class="son_box">This is son</div>
</div>
</template>
<script>
export default {
name: "",
data() {
return {};
},
created() {},
methods: {
getFather() {
console.log("触发了子组件的家");
},
},
};
</script>
效果:
法二:
父组件:
<template>
<div class="father">
<div class="father_box" @click="getSon">This is Father</div>
<son ref="son"></son>
</div>
</template>
<script>
import son from "@/components/son";
export default {
components: {
son,
},
methods: {
getSon() {
this.$refs.son.$emit("getSON")
},
},
};
</script>
子组件:
<template>
<div class="son">
<div class="son_box">This is son</div>
</div>
</template>
<script>
export default {
name: "",
data() {
return {};
},
mounted() {
this.$nextTick(function () {
this.$on("getSON", function () {
console.log("我是子组件方法");
});
});
},
methods: {},
};
</script>
效果:
赶快去试试吧