在SwiftUI中,可以通过以下几种方式将数据从一个ViewModel传递到另一个:
struct SourceView: View {
@StateObject var viewModel = SourceViewModel()
var body: some View {
VStack {
Text(viewModel.data)
NavigationLink(destination: DestinationView(data: $viewModel.data)) {
Text("Go to Destination")
}
}
}
}
struct DestinationView: View {
@Binding var data: String
var body: some View {
Text(data)
}
}
class SourceViewModel: ObservableObject {
@Published var data: String = "Hello World"
}
struct SourceView: View {
@StateObject var viewModel = SourceViewModel()
var body: some View {
VStack {
Text(viewModel.data)
NavigationLink(destination: DestinationView()) {
Text("Go to Destination")
}
}
.environmentObject(viewModel)
}
}
struct DestinationView: View {
@EnvironmentObject var viewModel: SourceViewModel
var body: some View {
Text(viewModel.data)
}
}
struct SourceView: View {
@StateObject var viewModel = SourceViewModel()
var body: some View {
VStack {
Text(viewModel.data)
NavigationLink(destination: DestinationView(data: { viewModel.data })) {
Text("Go to Destination")
}
}
}
}
struct DestinationView: View {
var data: () -> String
var body: some View {
Text(data())
}
}
这些方法可以根据具体的需求选择使用。在实际开发中,根据数据传递的复杂程度和应用场景的不同,可能会选择不同的方式来传递数据。
领取专属 10元无门槛券
手把手带您无忧上云