1、用vue脚手架工具生成myproject项目
2、用webstorm软件来open打开
3、这里的/src目录下有App.vue和main.js
这里app是入口,app加载的helloworld.vue组件
4、现在我们直接从App.vue做文档
粘贴一下实现代码
App.vue
<template>
<div id="app">
<h1>{{title}}</h1>
<input v-model="newItem" v-on:keyup.enter="addNewItem"/>
<ul>
<li v-for="item in items" v-bind:class="{finished:item.isFinished}" v-on:click="toggleFinish(item)">
{{item.label}}
</li>
</ul>
</div>
</template>
<script>
import store from './store'
export default {
data() {
return {
title: 'todo list',
items:store.fetch(),
newItem: '',
}
},
methods: {
toggleFinish: function (item) {
item.isFinished = !item.isFinished
},
addNewItem: function () {
//添加數組
this.items.push({
label: this.newItem, isFinished: false
}),
this.newItem = ''
}
},
watch:{
//监听items
items:{
handler:function (items) {
store.save(items)
},
deep:true
}
},
}
</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;
}
.finished {
text-decoration: underline;
}
</style>
说明一下,具体就是有一个点击事件来转换class,实现下划线的样式改变用到的指令是
v-on:click="toggleFinish(item)
第二个就是通过watch监听items数组来实现localstorage的存取,实现了f5重新刷新页面是,list数组仍然存在
这里的两个方法是fetch和save
代码如下:
store.js
const STORAGE_KEY = 'todos-vuejs'
//这里的常量可以随意定义,其实就是localstorage的key,val是一个[]数组
export default {
fetch() {
return JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '[]')
//第一次页面加载数组里面是空返回[],注意一定是windos,不是Windos,ws也不报错,一定要小心
},
save(items) {
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(items))
}
}
然后在App.vue中improt store.js
import store from './store'
然后就可以直接调用了
store.fetch(), ws有提醒哟
5、最后总结一哈
这里我们使用到几个vue的常用指令和localstoeage的使用以及es6的简单调用组件,dotolist这个经典案例是vue官网的一个简单明了的案例,下一篇更加详细的说组件的使用以及组件的参数传递调用,刚接触的时候类比于iframe子父页面的传参交互,/狗头