使用 Vue.js 和 Iris 共建一个简单的 Todo MVC 应用
本文用Golang的Iris框架作为后端服务,vuejs渲染前端UI,用websocket通信。基于监听hash变化 director.js库实现简单路由,axios库与后方沟通,netoffos.js库事件交流,小而美。
数据服务
package todo
import "sync"
// Item 条目数据
type Item struct {
SessionID string `json:"-"`
ID int64 `json:"id,omitempty"`
Title string `json:"title"`
Completed bool `json:"completed"`
}
// Service 通用接口
type Service interface {
Get(owner string) []Item
Save(owner string, newItems []Item) error
}
// MemoryService 内存服务存储结构
type MemoryService struct {
// 映射键为sessionid,值是携带sesseionid的item类型组成的列表
items map[string][]Item
// 并发访问读写锁
mu sync.RWMutex
}
// NewMemoryService 初始化
func NewMemoryService() *MemoryService {
return &MemoryService{
items: make(map[string][]Item, 0),
}
}
// Get 读
func (s *MemoryService) Get(sessionOwner string) []Item {
s.mu.RLock()
items := s.items[sessionOwner]
s.mu.RUnlock()
return items
}
// Save 写
func (s *MemoryService) Save(sessionOwner string, newItems []Item) error {
var prevID int64
for i := range newItems {
if newItems[i].ID == 0 {
newItems[i].ID = prevID
prevID++
}
}
s.mu.Lock()
s.items[sessionOwner] = newItems
s.mu.Unlock()
return nil
}
前端vuejs
<section class="main" v-show="todos.length" v-cloak="">
<input type="checkbox" v-model="allDone" class="toggle-all">
<ul class="todo-list">
<li v-for="todo in filteredTodos" class="todo" :key="todo.id"
:class="{ completed:todo.completed,editing:todo == editedTodo }">
<div class="view">
<input type="checkbox" @click="completeTodo(todo)" class="toggle">
<label @dblclick="editTodo(todo)">{{ todo.title }}</label>
<button @click="removeTodo(todo)" class="destroy"></button>
</div>
<input type="text" v-model="todo.title" v-todo-focus="todo==editedTodo" @blur="doneEdit(todo)"
@keyup.enter="doneEdit(todo)" @keyup.esc="cancelEdit(todo)" class="edit">
</li>
</ul>
</section>
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: