七亿少女的劫丨
学习Vue js 2.0 第一天-2
使用vue-cli( 脚手架) 创建vue项目
1.学会定义vue组件
2.标签化组件
目录结构:
主要关注src目录
Todos.vue 代码:
<template>
<ul class="list-group">
<li class="list-group-item"
v-bind:class="{'completed':todo.completed}"
v-for="(todo,index) in todos">{{todo.title}}
<button type="button" class="btn btn-warning btn-xs pull-right"
v-on:click="deletetodo(index)">deleted
</button>
<button type="button" class="btn btn-xs pull-right margin-right-10"
v-bind:class="[todo.completed ? 'btn-danger':'btn-success']"
v-on:click="toggleCompletion(todo)">{{todo.completed ? 'undo' :'completed'}}
</button>
</li>
</ul>
</template>
<script>
export default {
props:['todos'],
methods:{
deletetodo(index){
this.todos.splice(index,1)
},
toggleCompletion(todo){
todo.completed = ! todo.completed
}
}
}
</script>
<style scoped>
.completed {
color: #4cae4c;
text-decoration:line-through;
}
.margin-right-10{
margin-right: 10px;
}
</style>
TodoForm.vue代码:
<template>
<form v-on:submit.prevent="addtodo(newtodo)">
<div class="form-group" >
<input type="text" v-model="newtodo.title" class="form-control" placeholder="Add a new">
</div>
<div class="form-group">
<button class="btn btn-success" type="submit">Add Todo</button>
</div>
</form>
</template>
<script>
export default {
props:['todos'],
data(){
return{
newtodo:{id:null,title:'',completed:false}
}
},
methods:{
addtodo(newtodo) {
this.todos.push(newtodo);
this.newtodo={id:null,title:'',completed:false}
}
}
}
</script>
<style scoped>
</style>
在app.vue中声明 使用Todo.vue和TodoForm.vue
<template>
<div id="app">
<!--<img src="./assets/logo.png">-->
<!--<router-view/>-->
<todos :todos="todos"></todos>
<todo-form :todos="todos"></todo-form>
</div>
</template>
<script>
import TodoForm from "@/components/TodoForm"
import Todos from "@/components/Todos";
export default {
name: 'App',
data(){
return{
todos:[
{id:1,title:'learn Vue js',completed:false}
]
}
},
computed:{
todoCount(){
return this.todos.length
}
},
components: {TodoForm, Todos},
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
vue最好使用驼峰命名
注意Todos.vue,TodoForm.vue使用时,写成标签写为:
<todos :todos="todos"></todos>
<todo-form :todos="todos"></todo-form>
运行结果:
效果和使用CDN 引入vue js 2.0 效果一样
但是 文件,组件更加分散,便于管理,逼格更高!!!