1.开发环境 vuecli3
2.电脑系统 windows10专业版
3.在应用 vue开发的过后中,咱们常常会遇到组件传值的问题,上面我来分享一下vue中子组件向父组件传值的办法,心愿对你有所帮忙。
4.废话不多说,间接上代码:
//父组件代码:<template> <div> <p>我是父组件</p> <Chenperson1 :method="parentMethod"></Chenperson1> </div></template><script>import Chenperson1 from "@/components/Chenperson1.vue";export default { name: "ChenPerson", components: { Chenperson1, }, data() { return {}; }, mounted() {}, methods: { parentMethod(valueFromChild) { console.log('From the child:', valueFromChild); }, },};</script><style></style>
//子组件代码:<template> <div> <p>我是子组件一</p> </div></template><script>export default { name: "Chenperson1", props: { method: { type: Function }, }, data() { return { chenvalue:"I am the child", }; }, mounted() { this.method(this.chenvalue); }, methods: { ggg(){ } },};</script><style></style>
成果如下:
5.尽管下面的办法解决了子组件向父组件传值的问题,只是这不是在Vue中的最佳形式。相同,事件更适宜解决这个问题。咱们能够应用事件来实现完全相同的事件。
// 父组件代码:<template> <div> <p>我是父组件</p> <Chenperson1 @send-message="handleSendMessage"></Chenperson1> <button @click="gochild">去子组件一</button> </div></template><script>import Chenperson1 from "@/components/Chenperson1.vue";export default { name: "ChenPerson", components: { Chenperson1, }, data() { return {}; }, mounted() {}, methods: { handleSendMessage(event, value) { console.log('From the child:', event); }, gochild() { this.$router.push({ name: "chenperson1" }); }, },};</script><style></style>
// 子组件代码:<template> <div> <p>我是子组件一</p> </div></template><script>export default { name: "Chenperson1", props: { method: { type: Function }, }, data() { return { chenvalue:"I am the child", }; }, mounted() { this.$emit('send-message', this.chenvalue); }, methods: { ggg(){ } },};</script><style></style>
成果如下:
6.本期的分享到了这里就完结啦,心愿对你有所帮忙,让咱们一起致力走向巅峰。