vue ref和$refs获取组件实例
**创建 工程:
H:\java_work\java_springboot\vue_study
ctrl按住不放 右键 悬着 powershell
H:\java_work\java_springboot\js_study\Vue2_3入门到实战-配套资料\01-随堂代码素材\day04\准备代码\15-ref和$refs获取组件实例
vue --version
vue create v-ref-zj-demo
cd v-ref-zj-demo
npm run serve
App.vue
<template><div class="app"><h4>父组件 -- <button>获取组件实例</button></h4><BaseForm ref="baseForm"></BaseForm><button @click="handleGet">获取数据</button><button @click="handleReset">重置数据</button></div>
</template><script>
import BaseForm from "./components/BaseForm.vue";
export default {components: {BaseForm,},methods: {handleGet() {console.log(this.$refs.baseForm.getFormData());},handleReset() {},},
};
</script><style>
</style>
BaseForm.vue
<template><div class="app"><div>账号: <input v-model="username" type="text" /></div><div>密码: <input v-model="password" type="text" /></div><div><button @click="getFormData">获取数据</button><button @click="resetFormData">重置数据</button></div></div>
</template><script>
export default {data() {return {username: "admin",password: "123456",};},methods: {getFormData() {console.log("获取表单数据", this.username, this.password);return {username: "admin",password: "123456",};},resetFormData() {this.username = "";this.password = "";console.log("重置表单数据成功");},},
};
</script><style scoped>
.app {border: 2px solid #ccc;padding: 10px;
}
.app div {margin: 10px 0;
}
.app div button {margin-right: 8px;
}
</style>