为了方便记忆和学习,整理了一下之前学习VueJS的要点,并通过在中的代码注释来阐述知识点。
本章重点:使用router-link实现子元素/页面/组件跳转并获取相应数据。
GitHub前端代码 - liyingxuan/vue-cli-tutorial
GitHub后端代码 - liyingxuan/lara-vue-api
将之前代码重构
- ./src/router/index.js:
- 增加Todo路由
import Vue from 'vue'
import Router from 'vue-router'
import Todos from '@/components/Todos'
import Todo from '@/components/Todo'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Todos',
component: Todos
},
{
path: '/todo/:id',
name: 'todo',
component: Todo
}
]
})
- ./src/Todos.vue:
- 增加router-link
- 通过:to和name获取params提供给get的api使用
<template>
<div id="todos"> <!-- 这里的ID是用来声明template的 -->
<!-- 将显示数组数据部分组件化: -->
<ul class="list-group">
<!-- 通过v-bind来根据数据的不同设置class样式;把index输出,是为了提供删除使用 -->
<li class="list-group-item"
v-bind:class="{ 'completed' : todo.completed}"
v-for="(todo,index) in todos">
<router-link :to="{ name: 'todo', params: { id: todo.id }}">{{todo.title}}</router-link>
<button class="btn btn-success btn-xs pull-right"
v-bind:class="[todo.completed ? 'btn-danger' : 'btn-success']"
v-on:click="completedTodo(todo)">
{{ todo.completed ? 'undo' : 'done' }}
</button>
<button class="btn btn-warning btn-xs pull-right" v-on:click="delTodo(index)">Delete</button>
</li>
</ul>
<todo-form :todos="todos"></todo-form> <!-- 引入子组件 -->
</div>
</template>
<script>
import TodoForm from './TodoForm' // 引入子组件
export default {
name: 'Todos',
props: ['todos'], // 引入到组件中的数据/变量
methods: { // 逻辑方法
delTodo(index) {
this.todos.splice(index, 1)
},
completedTodo(todo){
todo.completed = !todo.completed
}
},
components: { // 引入子组件
TodoForm
}
}
</script>
<style>
.completed {
color: #00a379;
text-decoration: line-through;
}
</style>
- ./src/Todo.vue:
- 通过v-if控制div显示,这里只做了loading的,error的逻辑没做
- created() & watch:
<template>
<div class="todo">
<div class="loading" v-if="loading">
Loading...
</div>
<div v-if="error" class="error">
{{ error }}
</div>
<div v-if="todo" class="content">
<h2>{{ todo.title }}</h2>
</div>
</div>
</template>
<script>
export default {
data() {
return {
loading: false,
todo: null,
error: null
}
},
created() {
// 组件创建完后获取数据,
// 此时 data 已经被 observed 了
this.fetchData()
},
watch: {
// 如果路由有变化,会再次执行该方法
'$route': 'fetchData'
},
methods: {
fetchData() {
this.error = this.todo = null
this.loading = true
this.axios.get('http://localhost/api/todo/' + this.$route.params.id).then(response => {
this.todo = response.data
this.loading = false
})
}
}
}
</script>
The end.
→ VueJS-CLI学习教程 - 5 - 全套增删改查示例
← VueJS-CLI学习教程 - 3 - VueRouter
网友评论