vue ts父组件使用ref调用子组件的方法或获取子组件的值
vue2.0 ts父组件使用ref调用子组件的方法和值父组件中用ref绑定子组件,然后通过this.$refs.名字就可以获取子组件的值或调用相关方法。父组件<template><div><div class="parent"><h1>父组件名字:{{parentName}}</h1><a-button type="primary"
·
vue2.0 ts父组件使用ref调用子组件的方法和值
父组件中用ref绑定子组件,然后通过this.$refs.名字就可以获取子组件的值或调用相关方法。
父组件
<template>
<div>
<div class="parent">
<h1>父组件名字:{{parentName}}</h1>
<a-button type="primary" size="large" @click="refGetChildValue">
使用ref调用子组件的值
</a-button>
<div class="ref-function">
<a-button type="primary" size="large" @click="refGetChildFunction">
使用ref调用子组件的方法
</a-button>
</div>
</div>
<Child
ref="child"
/>
</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 {
parentName:string='父组件'
childEmitValue:any='';
//ref获取子组件的值
refGetChildValue(){
alert(this.$refs.child.childValue);
}
//ref调用子组件的方法
refGetChildFunction(){
this.$refs.child.childFunction();
}
}
</script>
子组件
<template>
<div>
<div class="child">
<div>
<h1>子组件</h1>
</div>
<div class="search">
<a-input-search
placeholder="传值给父组件"
enter-button="Emit传值给父组件"
size="large"
@search="onSearch"
/>
</div>
</div>
</div>
</template>
<script lang="ts">
import { Component, Vue, Prop,Emit } from "vue-property-decorator";
@Component({
components: {},
})
export default class Child extends Vue {
childValue:string="在路上,不需此行";
onSearch(value:any) {
console.log(value);
this.$emit('getChildInput',value);
}
childFunction(){
alert('我是子组件的方法');
}
}
</script>
ref获取子组件值效果图
ref调用子组件方法效果图
更多推荐
已为社区贡献7条内容
所有评论(0)