# vue
下面是分别使用WPF(Windows Presentation
Foundation)、React和Vue实现点击按钮后数值加一并在页面上显示变化的简单示例。这将帮助你了解三种技术在处理类似问题时的不同方法。
WPF 示例
首先,确保你已经安装了.NET SDK,并且熟悉XAML和C#语言。
1 2 3 4 5 6 7 8 9 10
| <Window x:Class="CounterApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Counter" Height="200" Width="300"> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <TextBlock Text="{Binding CounterValue}" FontSize="48"/> <Button Content="Increment" Command="{Binding IncrementCommand}" Width="150" Height="50"/> </StackPanel> </Window>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| using System.Windows; using System.Windows.Input;
namespace CounterApp { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = new MainViewModel(); } }
public class MainViewModel : BaseViewModel { private int _counterValue = 0;
public int CounterValue { get => _counterValue; set { _counterValue = value; OnPropertyChanged(nameof(CounterValue)); } }
public ICommand IncrementCommand { get; }
public MainViewModel() { IncrementCommand = new RelayCommand(Increment); }
private void Increment(object obj) { CounterValue++; } } }
|
这里我们使用了MVVM模式,MainViewModel
作为视图模型管理数据和命令逻辑。
React 示例
接下来是React版本,使用函数组件和Hooks。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import React, { useState } from 'react';
function Counter() { const [count, setCount] = useState(0);
return ( <div style={{textAlign: 'center', marginTop: '50px'}}> <h1>{count}</h1> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }
export default Counter;
|
这个例子非常直观,利用了useState
Hook来管理状态。
Vue 示例
最后是Vue版本,同样简洁明了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <template> <div style="text-align: center; margin-top: 50px;"> <h1>{{ count }}</h1> <button @click="increment">Increment</button> </div> </template>
<script setup> import { ref } from 'vue';
const count = ref(0);
function increment() { count.value++; } </script>
|
在这个Vue的例子中,我们使用data
选项定义了一个响应式属性count
,并用methods
选项添加了一个增加计数的方法。
总结
- WPF:
使用MVVM设计模式,通过绑定机制将UI与逻辑分离,适合构建复杂的桌面应用程序。
- React:
基于组件和状态管理,使用JSX语法混合HTML和JavaScript代码,非常适合Web应用开发。
- Vue:
结合模板和脚本部分,易于理解和学习,也提供了灵活的状态管理方案,适用于快速Web开发。
每个框架或平台都有其独特的优势,选择哪一个取决于项目需求和个人偏好。