Vue如何在另一个.vue文件更新数据?Cookie Clicker克隆开发求助
核心问题
你直接通过import App然后访问App.clickPoint的方式完全错误——App是组件的构造函数,不是当前运行的父组件实例,根本无法获取和修改父组件的实时数据。Vue父子组件的正确交互逻辑是父传子用props,子改父用事件触发。
正确实现步骤
- 父组件向子组件传数据:通过props把父组件的
clickPoint传给Upgrade子组件,让子组件能判断是否够买升级。 - 子组件触发父组件方法改数据:子组件不能直接修改props,要通过
$emit触发父组件定义的方法,由父组件自己更新clickPoint和summand。 - 子组件维护自身状态:升级成本(cursorCost、receptCost)属于子组件自己的状态,直接在子组件内更新即可。
修改后的代码
App.vue
<template> <div id="clickPower"> <h1>Click Power: {{summand}}</h1> </div> <h1 id="clickPoint">{{clickPoint}}</h1> <div id="cookie"> <button @click="clicked"> <img src="../res/img/Cookie.png" alt="Cookie"> </button> </div> <!-- 传递父组件的clickPoint,绑定子组件触发的事件 --> <Upgrade :click-point="clickPoint" @buy-cursor="handleBuyCursor" @buy-recept="handleBuyRecept" /> </template> <script> import Upgrade from "./components/Upgrade.vue"; export default { name: "App", data() { return { clickPoint: 0, summand: 1, }; }, components: { Upgrade, }, methods: { clicked() { this.clickPoint += this.summand; }, // 处理购买光标升级的方法 handleBuyCursor(cost) { this.clickPoint -= cost; this.summand += 1; }, // 处理购买配方升级的方法 handleBuyRecept(cost) { this.clickPoint -= cost; this.summand += 3; } }, }; </script> <style scoped> @import './assets/main.css'; </style>
Upgrade.vue
<template> <div id="upClickCursor"> <button @click="upClickCursor"> <img src="../../res/img/Cursor.png" alt="Cursor"> </button> <p>{{cursorCost}}</p> </div> <div id="upClickRecept"> <button @click="upClickRecept"> <img src="../../res/img/Recept.png" alt="Recept"> </button> <p>{{receptCost}}</p> </div> </template> <script> // 删除无用的App组件导入 export default { name: "Upgrade", // 通过props接收父组件传递的clickPoint props: { clickPoint: { type: Number, required: true } }, data() { return { cursorCost: 10, receptCost: 20, }; }, methods: { upClickCursor() { if (this.clickPoint >= this.cursorCost) { // 触发父组件的购买方法,传递当前成本 this.$emit('buy-cursor', this.cursorCost); // 更新子组件自身的升级成本 this.cursorCost += 15; } }, upClickRecept() { if (this.clickPoint >= this.receptCost) { this.$emit('buy-recept', this.receptCost); this.receptCost += 25; } } }, }; </script> <style scoped> @import '../assets/Upgrade.css'; </style>
关键说明
- props传递规则:父组件用
:click-point="clickPoint"传递数据(短横线命名会自动对应子组件内的驼峰式clickPoint,这是Vue的自动转换规则)。 - 事件触发逻辑:子组件通过
this.$emit('事件名', 参数)触发父组件绑定的方法,把升级成本这类必要参数传给父组件处理。 - 单向数据流:Vue要求props是只读的,子组件绝对不能直接修改props,必须由父组件自己更新数据,这能避免数据状态混乱,是Vue的核心设计规则。
内容的提问来源于stack exchange,提问作者user18773012
相关产品推荐
相关产品推荐

