① vuex(状态管理):
vue cli 2 中 :vuex是搭建完成后自己npm install的,并不包括在搭建过程中。可以看到vue cli 2的vuex默认文件夹(store)又包含了三个js文件:action(存放一些调用外部API接口的异步执行的的方法,然后commit mutations改变mutations 数据)、index(初始化mutations 数据,是store的出口)、mutations(处理数据逻辑的同步执行的方法的集合,Vuex中store数据改变的唯一方法commit mutations)
vue cli 3 中:vuex是包含在搭建过程供选择的预设。vue cli 3 中默认只用一个store.js代替了原来的store文件夹中的三个js文件。action、mutations、state以及store 的 getters 的用法有很多,举常用的例子:
eg:store.js
import Vue from 'vue';
import Vuex from 'vuex'; //引入 vuex
import store from './store' //注册storeVue.use(Vuex); //使用 vuex
export default new Vuex.Store({
state: {
// 初始化状态
count: 0
},
mutations: {
// 处理状态
increment(state, payload) {
state.count += payload.step || 1;
}
},
actions: {
// 提交改变后的状态
increment(context, param) {
context.state.count += param.step;
context.commit('increment', context.state.count)//提交改变后的state.count值
},
incrementStep({state, commit, rootState}) {
if (rootState.count < 100) {
store.dispatch('increment', {//调用increment()方法
step: 10
})
}
}
}
})
使用时,eg:
main.js:
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store' //引入状态管理 storeVue.config.productionTip = false
new Vue({
router,
store,//注册store(这可以把 store 的实例注入所有的子组件)
render: h => h(App)
}).$mount('#app')
views/home.vue:
<template>
<div class="home">
<!--在前端HTML页面中使用 count-->
<HelloWorld :msg="count"/>
</div>
</template><script>
import HelloWorld from '@/components/HelloWorld.vue'
import {mapActions, mapState} from 'vuex' //注册 action 和 state
export default {
name: 'home',
computed: {
//在这里映射 store.state.count,使用方法和 computed 里的其他属性一样
...mapState([
'count'
]),
},
created() {
this.incrementStep();
},
methods: {
//在这里引入 action 里的方法,使用方法和 methods 里的其他方法一样










