实现简易的todolist
安装
$ cnpm install -g vue-cli
$ vue
# 回车,若出现vue信息说明表示成功
# 创建一个基于 webpack 模板的新项目
$ vue init webpack my-project
# 这里需要进行一些配置,默认回车即可
This will install Vue 2.x version of the template. -->
技术准备
<!-- vue是mvvm模型,自底向上逐层应用,用于构建用户界面的渐进式框架。 -->
<!-- 挂载点 挂载点内部的为模板。 -->
<!-- 操作数据 -->
<!-- 例1 -->
<div id="root">{{msg}}</div>
<script>
new Vue({ //vue实例
el: '#root', //接管element
template: "<h1>hello world</h1>", //模板
data: {
msg: "hello world"
}
})
</script>
<!-- 例2 -->
<div v-html='content' class="div" v-on:click="handclick"></div>
<div v-text='content' class="div" @click="handclick"></div>
<script>
new Vue({
el: '.div',
data: {
content: '<h1>hello world</h1>'
},
methods: {
handclick: function() {
alert(123);
this.content = '<h1>你好世界</h1>';
}
}
});
</script>
监听器和属性的计算
输入姓和名 输出全名 并计算全名的字数
<div class="root">
姓:<input type="text" v-model='firstName'>名:<input type="text" v-model='nextName'>
<div v-html='fullName' v-bind:title='title'></div>
<div>{{count}}</div>
</div>
<script>
new Vue({
el: '.root',
// template: "<h1>hi</h1>",
data: {
firstName: '',
nextName: '',
title: '全名',
count: 0
},
methods: {
fn: function() {
}
},
computed: { //属性计算
fullName: function() {
return this.firstName + " " + this.nextName;
}
},
watch: { //侦听器
firstName: function() {
this.count++;
},
nextName: function() {
this.count++;
}
}
});
</script>
条件与循环渲染
<div class="show" v-if="show" @click='handclick'>
{{content}}
<div v-for='(item,key,value) of obj'>{{item}}---{{key}}---{{value}}</div>
</div>
<script>
// v-if:控制dom的存在与否,v-show:控制dom的显示与否,v-for:循环操作
new Vue({
el: '.show',
// template: '<h1>welcome</h1>',
data: {
show: true,
content: 'welcome',
list: [1, 2, 3],
obj: {
name: 'pancong',
sex: 'men',
age: 19,
id: 110
}
},
methods: {
handclick: function() {
this.show = false;
}
}
})
</script>
todolist 实现
html
<div id="box">
<div id="top">
<input type="text" id="text" v-model='inputValue' @keydown.enter='handSubmit'>
</div>
<div id="content">
<h2>正在进行<span>{{list.length}}</span></h2>
<ul id="doing">
<todo-item v-for="(item,index) of list" :key='index' :content='item' :content='index' @delete='handdelete'>
</todo-item>
</ul>
<!-- <h2>已经完成<span>0</span></h2>
<ul id="done"></ul> -->
</div>
</div>
js
<script>
Vue.component('todo-item', { //全局组件
props: ['content', 'index'],
template: '<li @click="handclick" v-html="content"></li>',
methods: {
handclick: function() {
this.$emit('delete', this.index); //向外抛出一个事件
}
}
});
var todoitem = { //局部组件,需要在实例中声明
}
new Vue({
el: '#box',
// components: { //组件声明属性
// "todo-item": todoitem
// },
data: {
inputValue: '',
list: [],
clearbtn: true
},
methods: {
handSubmit: function(e) {
console.log(e);
// if (e.keyCode == 13) {
this.list.push('<input type="checkbox"><p contenteditabled>' + this.inputValue + '</p><a href="#">删除</a>');
this.inputValue = ''
// }
},
handdelete: function(index) {
this.list.splice(index, 1);
}
}
})
</script>