[TOC]
## :-: 添加vuex
```
$ vue add vuex -- 集中式存儲管理
```
*****
## :-: 項目運用
:-: main.js
```
import Vue from 'vue'
import App from './App.vue';
import router from './router.js';
import './plugins/axios';
//在這里引入 bootstrap。默認只引入 bootstrap 中的 js,css 需要另外引入,我的 bootstrap.ss 在APP.vue中引入的
import "bootstrap";
//也可以在這里引入 bootstrap.css ;
import "bootstrap/dist/css/bootstrap.min.css";
import x2js from 'x2js' //xml數據處理插件
// vue add vuex -- 數據倉庫
import store from './store'
Vue.config.productionTip = false;
Vue.prototype.$x2js = new x2js() //創建x2js對象,掛到vue原型上
// 全局守衛 (main.js)
// 進頁面前觸發
router.beforeEach((to, from, next) => {
// if (['student', 'academic'].includes(to.name)) return;
// some every
let needLogin = to.matched.some(ele => ele.meta && ele.meta.login === true);
if (needLogin) {
// 判斷是否需要登陸
let isLogin = document.cookie.includes('login=true');
if (isLogin) {
next();
} else {
isLogin = window.confirm('該頁面需要登陸后才能訪問 ~');
if (isLogin) {
next('/login');
}
// 需要登陸
}
} else {
next();
}
});
// // 解析完畢執行
// router.beforeResolve((to, from, next) => {
// // to and from are both route objects. must call `next`.
// // next();
// })
new Vue({
router, store, render: h => h(App)
}).$mount('#app');
```
:-: **store.js**
```
// store.js -- 相當于是一個數據存儲的倉庫
import Vue from 'vue';
import Vuex from 'vuex';
//
import learn from './store/learn';
Vue.use(Vuex);
// $store state $store.state
// this.$store.state.xxx
// mapState([]) mapState({})
export default new Vuex.Store({
// strict -- 開啟嚴格模式 (在不為生產模式的時候開啟,上線后最好關掉)
// strict: process.env.NODE_ENV !== 'production',
strict: false,
// state -- 用于存儲數據、
state: {
// const
nowAdd: {},
tableData: []
},
// 模塊
modules: {
abc: {
state: {},
getters: {},
mutations: {},
actions: {}
},
learn
},
// getters -- 用于計算屬性、
getters: {
// 類似于計算屬性、
// 映射 在標簽中通過 $store.getters.person 拿到數據、
person(state) {
// console.log(state);
return `姓名:${state.nowAdd.name} 年齡:${state.nowAdd.age}`;
}
},
mutations: {
// 只能執行同步的
// 改變vuex中的狀態
// 用法 this.$store.commit('xxx')
// mapMutations(['xxx'])
// mapMutations({newXXX:'xxx'})
addTableData(state, obj) {
// console.log(state, obj);
state.tableData.push(obj);
}
},
actions: {
// 能夠執行異步
// 提交mutations,讓mutations去更改狀態、
// 要用到異步時,使用actions
// 用法 this.$store.dispatch('xxx')
// mapActions(['xxx'])
// mapActions({newXXX:'xxx'})
addTableData({ commit }, payload) {
setTimeout(() => {
commit('addTableData', payload)
}, 1000);
}
}
})
```
*****
:-: ./Student.vue
```
<template>
<div class="student">
<div class="panel panel-default">
<div class="panel-heading" style="background-color:#fff;">
<!-- add-student -->
<add-student />
</div>
<!-- Table -->
<student-list />
</div>
</div>
</template>
<script>
import addStudent from "@/components/Student/AddStudent";
import studentList from "@/components/Student/StudentList";
export default {
components: { addStudent, studentList }
};
</script>
```
:-: ./Student/AddStudent.vue
```
<template>
<div class="add-student" style="max-width: 300px;">
<div class="form-group">
<label for="exampleInput_sd41f">姓名:</label>
<input class="form-control" id="exampleInput_sd41f" v-model="nowAdd.name" placeholder="張三" />
</div>
<div class="form-group">
<label for="exampleInput_sdi25">年齡:</label>
<input class="form-control" id="exampleInput_sdi25" v-model="nowAdd.age" placeholder="18" />
</div>
<button class="btn btn-default" @click="addRow({name:nowAdd.name,age:nowAdd.age})">添加</button>
</div>
</template>
<script>
import { mapState, mapMutations, mapActions } from "vuex";
// console.log(mapState(["name", "age", "look"]));
// this.$store.state.nowAdd = {};
export default {
methods: {
...mapMutations(["addTableData"]),
// ...mapActions(["addTableData"]),
addRow(obj) {
// 更新視圖數據、
this.$set(this.nowAdd, "name", "");
this.$set(this.nowAdd, "age", "");
if (!obj.name && !obj.age) return;
obj.id = +new Date();
// console.log(obj);
// this.$store.state.tableData.push(obj);
// this.$store.commit("addTableData", obj);
this.addTableData(obj);
// 異步
// this.$store.dispatch("addTableData", { obj, name: "abc" });
// this.addTableData(obj);
}
},
// 計算屬性
computed: {
// ES7 - 點點點運算符
...mapState(["nowAdd"])
// ...mapState(["age"]),
// ...mapState({
// // 自定義命名
// myName: state => state.name
// })
}
};
</script>
```
:-: ./Student/StudentList.vue
```
<template>
<div class="Student-list">
<!-- Table -->
<!-- v-if="(tableData.length||name||age)" -->
<table class="table" style="margin:0;">
<thead>
<tr>
<th style="width:80px;">#</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in tableData" :key="item.id">
<th>{{index+1}}</th>
<td>{{item.name}}</td>
<td>{{item.age}}</td>
</tr>
<tr v-show="nowAdd.name||nowAdd.age" style="color:#bbb;">
<th>{{tableData.length+1}}</th>
<td>{{nowAdd.name}}</td>
<td>{{nowAdd.age}}</td>
</tr>
</tbody>
</table>
<!-- 類似于計算屬性、 -->
<!-- <p>{{$store.getters.person}}</p> -->
<!-- <p>{{person}}</p> -->
<!-- <p>{{newPerson}}</p> -->
</div>
</template>
<script>
// import { mapState } from "vuex";
// mapGetters -- 可以拿到 $store.getters
import { mapState, mapGetters } from "vuex";
export default {
computed: {
...mapState(["tableData", "nowAdd"]),
// ...mapGetters(["person"]),
...mapGetters({
// 取一個別名
newPerson: "person"
})
}
};
</script>
```
*****
:-: ./store/learn.js
```
export default {
// 添加命名空間
namespaced: true,
state: { learnData:'模塊數據' },
getters: {
coursePrice() {
return 'abc';
}
},
mutations: {},
actions: {}
};
```
## :-: vue - 修改state的方法 (標準)
:-: vuex的理念是單向數據流
```
// --------------- state
// 開啟嚴格模式,對代碼進行嚴格檢測
strict: process.env.NODE_ENV !== 'production'
state:{
// 數據
xxx:'xxx',
studentList:[]
},
mutations:{
// 該對象存放的是同步的操作
changelist(state,{name,objData}){
state.studentList.push(objData);
}
},
actions:{
// 執行異步的,可以重名
changelist( {commit}, payload ){
setTimeout(()=>{
commit('changelist', payload)
},1000)
}
}
// --------------- 外部調用方式
// 執行同步
this.$state.commit('changelist',abc);
// 執行異步
this.$state.dispatch('changelist');
-- 導入方式調用
import { mapMutations, mapActions } from 'vuex';
methods:{
...mapMutations(['changelist']),
...mapActions(['changelist'])
}
```
## :-: vuex - 分模塊管理數據
```
-- 分模塊管理 (在vuex對象中增加modules屬性)
modules:{
modulesTest:{
namespaced: true, // 添加上命名空間,定義為模塊
state:{
// 數據
xxx:'xxx',
studentList:[]
},
getters:{
xxx(){ return xxx; }
},
mutations:{
// 該對象存放的是同步的操作
changelist(state,{name,objData}){ state.studentList.push(objData); }
},
actions:{
// 執行異步的,可以重名
changelist( {commit}, payload ){
setTimeout(()=>{ commit('changelist', payload) },1000)
}
}
}
}
// --------------- 外部調用方式
// 1. state放入到每一個模塊中,getters、mutations、actions會被放置到全局下。
// 2. 但是這么做顯然不科學,所以我們需要定義上一個命名空間 (namespaced:true)
第一種調用方式:
// 獲取'modulesTest'模塊下state對象中的數據'xxx'
this.$store.state['modulesTest'].xxx
// 調用'modulesTest'模塊下getters對象中的'xxx'方法 (計算屬性)
this.$store['modulesTest/getters'].xxx
// 調用'modulesTest'模塊下mutations對象中的'changelist'方法 (同步)
this.$store.commit('modulesTest/changelist', {abc,123} );
// 調傭'modulesTest'模塊下actions對象中的'changelist'方法 (異步)
this.$store.dispatch('modulesTest/changelist', {abc,123} );
第二種調用方式:
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex';
computed:{
// modulesTest -- 是模塊的命名空間
...mapState('modulesTest', ['xxx']),
...mapGetters('modulesTest', ['xxx'])
},
methods:{
...mapMutations('modulesTest', ['changelist']),
...mapActions('modulesTest', {
// 傳入對象的方式可以更換別名 (this.xxx)
changelist:'xxx'
}),
}
```
- 前端工具庫
- HTML
- CSS
- 實用樣式
- JavaScript
- 模擬運動
- 深入數組擴展
- JavaScript_補充
- jQuery
- 自定義插件
- 網絡 · 后端請求
- css3.0 - 2019-2-28
- 選擇器
- 邊界樣式
- text 字體系列
- 盒子模型
- 動圖效果
- 其他
- less - 用法
- scss - 用法 2019-9-26
- HTML5 - 2019-3-21
- canvas - 畫布
- SVG - 矢量圖
- 多媒體類
- H5 - 其他
- webpack - 自動化構建
- webpack - 起步
- webpack -- 環境配置
- gulp
- ES6 - 2019-4-21
- HTML5補充 - 2019-6-30
- 微信小程序 2019-7-8
- 全局配置
- 頁面配置
- 組件生命周期
- 自定義組件 - 2019-7-14
- Git 基本操作 - 2019-7-16
- vue框架 - 2019-7-17
- 基本使用 - 2019-7-18
- 自定義功能 - 2019-7-20
- 自定義組件 - 2019-7-22
- 腳手架的使用 - 2019-7-25
- vue - 終端常用命令
- Vue Router - 路由 (基礎)
- Vue Router - 路由 (高級)
- 路由插件配置 - 2019-7-29
- 路由 - 一個實例
- VUEX_數據倉庫 - 2019-8-2
- Vue CLI 項目配置 - 2019-8-5
- 單元測試 - 2019-8-6
- 掛載全局組件 - 2019-11-14
- React框架
- React基本使用
- React - 組件化 2019-8-25
- React - 組件間交互 2019-8-26
- React - setState 2019-11-19
- React - slot 2019-11-19
- React - 生命周期 2019-8-26
- props屬性校驗 2019-11-26
- React - 路由 2019-8-28
- React - ref 2019-11-26
- React - Context 2019-11-27
- PureComponent - 性能優化 2019-11-27
- Render Props VS HOC 2019-11-27
- Portals - 插槽 2019-11-28
- React - Event 2019-11-29
- React - 渲染原理 2019-11-29
- Node.js
- 模塊收納
- dome
- nodejs - tsconfig.json
- TypeScript - 2020-3-5
- TypeScript - 基礎 2020-3-6
- TypeScript - 進階 2020-3-9
- Ordinary小助手
- uni-app
- 高德地圖api
- mysql
- EVENTS
- 筆記
- 關于小程序工具方法封裝
- Tool/basics
- Tool/web
- parsedUrl
- request