Skip to content

Instantly share code, notes, and snippets.

@YanceyOfficial
Last active March 13, 2019 11:08
Show Gist options
  • Save YanceyOfficial/24e306d68decbca19e3d06dda8ee1a53 to your computer and use it in GitHub Desktop.
Save YanceyOfficial/24e306d68decbca19e3d06dda8ee1a53 to your computer and use it in GitHub Desktop.
Vue组件间通信
// 父组件
<template>
<div class="home">
<Child
staticTxt="向子组件传递静态文字"
:propValue="propValue"
@parentMethod2="parentMethod2"
:parentMethod3="parentMethod3"
/>
</div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import Child from '@/components/Child.vue';
@Component({
components: {
Child,
},
})
export default class Home extends Vue {
public propValue: string = '向子组件传递属性值';
public parentMethod1(value: string) {
alert(`我是父组件方法1, 我接受到子组件传递来的值:${value}`);
}
public parentMethod2(value: number) {
alert(`我是父组件方法2, 我接受到子组件传递来的值:${value}`);
}
// 其中通过props的方式最合理
public parentMethod3(value: number) {
alert(`我是父组件方法3, 我接受到子组件传递来的值:${value}`);
}
}
</script>
// 子组件
<template>
<section class="child_component_wrapper">
<p>{{staticTxt}}</p>
<p>{{propValue}}</p>
<button @click="getParentMethod1">子组件调用父组件方式一</button>
<button @click="getParentMethod2">子组件调用父组件方式二</button>
<button @click="getParentMethod3">子组件调用父组件方式三</button>
</section>
</template>
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
@Component
export default class Child extends Vue {
@Prop() private staticTxt!: string;
@Prop() private propValue!: string;
@Prop({ required: true, type: Function }) private parentMethod3!: (
value: number,
) => void;
public getParentMethod1() {
this.$parent.parentMethod1(1);
}
public getParentMethod2() {
this.$emit('parentMethod2', 2);
}
public getParentMethod3() {
this.parentMethod3(3);
}
}
</script>
<style scoped lang="scss">
button {
margin: 4px;
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment