Skip to content

实现 买房租房对比 工具

分类:general | 标签:买房、租房、决策 对比买房与租房的资金差异

2.1 功能说明

对比买房与租房的资金差异

2.1.1 使用指南

功能说明

对比同等居住条件下,买房与租房 N 年后的净资金差异(含贷款利息、房价涨幅、租金涨幅、机会成本)。

使用场景

置业决策、理财规划。

2.2 代码实现

2.2.1 组件结构

本工具是一个基于 Vue 3 <script setup> 语法的单文件组件(SFC),统一包裹在 ToolPageShell 组件内,由它提供页面标题、工具 ID、分类与「使用指南」插槽等通用外壳;核心业务逻辑(响应式状态、计算属性、事件处理函数)全部写在 <script setup> 中,输入/输出通过 el-inputel-button 等 Element Plus 组件与用户交互,所有数据均在浏览器本地处理,不会上传服务器。

2.2.2 核心逻辑概览

<script setup> 中定义的主要函数/方法:

  • run()

2.2.3 关键实现代码

以下是该工具的完整 <script setup> 实现(核心代码)。模板(<template>)与样式(<style>)已省略。

vue
import { ref } from 'vue'
import ToolPageShell from '@/components/ToolPageShell.vue'

const price = ref(300), down = ref(30), rate = ref(4.2), years = ref(30)
const rent = ref(4000), hpGrowth = ref(3), rentGrowth = ref(3), invest = ref(4), span = ref(10)
const error = ref(''), res = ref(null)

function run() {
  error.value = res.value = null
  const P = Number(price.value) * 10000
  const dp = Number(down.value) / 100, r = Number(rate.value) / 100 / 12
  const n = Number(years.value) * 12, Y = Number(span.value)
  if (![P, dp, r, n, Y].every(Number.isFinite) || P <= 0 || Y <= 0) { error.value = '请填写有效正数'; return }
  const loan = P * (1 - dp)
  const pmt = r === 0 ? loan / n : loan * r / (1 - Math.pow(1 + r, -n))
  // total interest paid over Y years
  let bal = loan, paid = 0
  for (let m = 0; m < Y * 12; m++) { const intr = bal * r; bal = bal + intr - pmt; paid += pmt }
  const downPay = P * dp
  const buyCost = downPay + paid // money sunk into housing (ignoring appreciation)
  // house value after Y years
  const houseValue = P * Math.pow(1 + Number(hpGrowth.value) / 100, Y)
  const buyNet = houseValue - bal // asset minus remaining loan
  // rent scenario: invest down payment + monthly difference (pmt - rent) grows at invest%
  let asset = downPay
  let monthlyRent = Number(rent.value)
  const invM = Number(invest.value) / 100 / 12
  for (let m = 0; m < Y * 12; m++) {
    const save = (pmt - monthlyRent)
    asset = (asset + save) * (1 + invM)
    if ((m + 1) % 12 === 0) monthlyRent *= (1 + Number(rentGrowth.value) / 100)
  }
  const diff = asset - buyNet
  res.value = {
    buyCost, rentAsset: asset,
    verdict: diff > 0 ? `租房+投资更优,约多 ${diff.toFixed(0)} 元` : `买房更优,约多 ${(-diff).toFixed(0)} 元`
  }
}

2.3 效果截图

买房租房对比 效果截图

工具访问地址:https://www.i91tools.com/tools/buy-vs-rent