Vue CLI
Vue CLI 是一个基于 Vue.js 进行快速开发的完整系统
# 全局安装脚手架
cnpm install -g @vue/cli
# 快速创建一个项目
vue create todos
# 打开项目
cd todos
# 运行项目
cnpm run serve --open
VueX
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。每一个 Vuex 应用的核心就是 store(仓库)
- 驱动应用的数据源
state: {
todos:[
{
id:1,skill:'学习vue',bool:true},
{
id:2,skill:'学习react',bool:true},
{
id:3,skill:'学习angular',bool:false}
]
},
- mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。可以直接使用state状态,受 state 作为第一个参数
mutations: {
del(state,id){
console.log(state.todos.filter(item=>item.id!==id))
}
},
created(){
this.$store.commit("del",1)
}
- action:Action 提交的是 mutation,而不是直接变更状态。Action 可以包含任意异步操作。
actions: {
del(context,id) {
context.commit("del",id);
},
},
created(){
this.$store.dispatch("del",1);
}
- getters:就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
getters:{
getid(state){
return '1111'
}
}
<div id="app">
{
{this.$store.getters.getid}}
</div>
- module将store分割成模块
const moduleA = {
state: {
... },
mutations: {
... },
actions: {
... },
getters: {
... }
}
const moduleB = {
state: {
... },
mutations: {
... },
actions: {
... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
实现todos
使用模板
- 下载模板文件
git clone https://github.com/tastejs/todomvc-app-template.git --depth 1
- 将index.html的代码抽离出来放在我们Vue的组件里面(App.vue)
<section class="todoapp">
<header class="header">
<h1>todos</h1>
<input class="new-todo" placeholder="What needs to be done?" autofocus>
</header>
<!-- This section should be hidden by default and shown when there are todos -->
<section class="main">
<input id="toggle-all" class="toggle-all" type="checkbox">
<label for="toggle-all">Mark all as complete</label>
<ul class="todo-list">
<!-- These are here just to show the structure of the list items -->
<!-- List items should get the class `editing` when editing and `completed` when marked as completed -->
<li class="completed">
<div class="view">
<input class="toggle" type="checkbox" checked>
<label>Taste JavaScript</label>
<button class="destroy"></button>
</div>
<input class="edit" value="Create a TodoMVC template">
</li>
<