我们在进行vue开发时会将公共的部分进行抽象,然后生成一个独立的组件,这个组件可以被其它页面引用,如果希望有交互的动作就设计到了值的传递,或者方法的回调等问题,这一次我们主要来说一下父组件和子组件的交互。

值的传递

子组件,通过定义了prods,然后可以实现从父组件向子组件的传递:

  <template>
<div id="app">
这是自定义的组件:{{myMessage}}
<button @click="childClick">调用父组件的方法</button>
</div>
</template>
<script>
export default {
name: "testComponent",
props: ["myMessage"],
data() {
return {
message: "hello world",
myNum: 37,
myStr: "lind"
};
},
methods: {
childClick() {
console.log("调用childClick");
this.$emit("abcClick", this.myNum, this.myStr);
}
}
};
</script>

父组件/页面,直接为这个prods赋值即可,注意如果JS里props名称是小驼峰,在html需要用中线来代替

    <testComponent my-message="hello"></testComponent>
<script>
import testComponent from "@/components/testComponent";
export default {
name: "test-grammer",
props: {
//接收父组件传递过来的参数
},
components: {
testComponent
}
}
</script>

方法的传递/回调

在父页面绑定子组件的方法,然后子组件在某个时机去触,这就形成了在子组件里调用父组件的方法,使用了$emit来实现

 <button @click="childClick">调用父组件的方法</button>
<script>
export default {
name: "testComponent",
methods: {
childClick() {
this.$emit("abcClick", this.myNum, this.myStr);
}
}
};
</script>

在父页面中去绑定这个abcClick事件就可以了,当在子组件调用这个childClick事件时,绑定了abcClick的方法将会被一起回调

<testComponent  @abcClick="sayHello"></testComponent>
<script>
import testComponent from "@/components/testComponent";
export default {
name: "test-grammer",
methods: {
sayHello(Num, Str) {
console.log("hello world~~" + Num + Str);
}
},
};
</script>

1.《vue~父组件与子组件的交互》援引自互联网,旨在传递更多网络信息知识,仅代表作者本人观点,与本网站无关,侵删请联系页脚下方联系方式。

2.《vue~父组件与子组件的交互》仅供读者参考,本网站未对该内容进行证实,对其原创性、真实性、完整性、及时性不作任何保证。

3.文章转载时请保留本站内容来源地址,https://www.cxvn.com/study/26717.html