vue-cli+webpack记事本项目创建

2020-06-16 05:38:39易采站长站整理

class="form-control"
v-model="comment"
placeholder="Comment"
/>
</div>
</div>
<button class="btn btn-primary" @click="save()">保存</button>
<router-link to="/time-entries" class="btn btn-danger">取消</router-link>
<hr>
</div>
</template>

<script>
export default {
name : 'LogTime',
data() {
return {
date : '',
totalTime : '',
comment : ''
}
},
methods:{
save() {
const plan = {
name : '二哲',
image : 'https://sfault-avatar.b0.upaiyun.com/888/223/888223038-5646dbc28d530_huge256',
date : this.date,
totalTime : this.totalTime,
comment : this.comment
};
this.$store.dispatch('savePlan', plan)
this.$store.dispatch('addTotalTime', this.totalTime)
this.$router.go(-1)
}
}
}
</script>

这个组件很简单就3个input输入而已,然后就两个按钮,保存我们就把数据push进我们store的列表里

LogTime 属于我们 TimeEntries 组件的一个子路由,所以我们依旧需要配置下我们的路由,并且利用webpack让它懒加载,减少我们首屏加载的流量


// src/main.js
//...
const routes = [{
path : '/',
component : Home
},{
path : '/home',
component : Home
},{
path : '/time-entries',
component : TimeEntries,
children : [{
path : 'log-time',
// 懒加载
component : resolve => require(['./components/LogTime.vue'],resolve),
}]}];

//...

vuex部分

在vue2.0中废除了使用事件的方式进行通信,所以在小项目中我们可以使用Event Bus,其余最好都使用vuex,本文我们使用Vuex来实现数据通信

相信你刚刚已经看见了我写了很多 this.$store.dispatch(‘savePlan’, plan) 类似这样的代码,我们再次统一说明。

仔细思考一下,我们需要两个全局数据,一个为所有计划的总时间,一个是计划列表的数组。

src/store/index.js 没啥太多可介绍的,其实就是传入我们的 state , mutations, actions 来初始化我们的Store。如果有需要的话我们还可能需要创建我们的 getter在本例中就不用了。

接着我们看 mutation-types.js ,既然想很明确了解数据,那就应该有什么样的操作看起,当然这也看个人口味哈


// src/store/mutation-types.js

// 增加总时间或者减少总时间
export const ADD_TOTAL_TIME = 'ADD_TOTAL_TIME';
export const DEC_TOTAL_TIME = 'DEC_TOTAL_TIME';

// 新增和删除一条计划
export const SAVE_PLAN = 'SAVE_PLAN';
export const DELETE_PLAN = 'DELETE_PLAN';
// src/store/mutations.js
import * as types from './mutation-types'