wordpress平台,什么是优化设计,长春微信推广,wordpress注册跳过邮箱验证码一、vuex概述
目标#xff1a;明确vuex是什么#xff0c;应用场景#xff0c;优势
1. 是什么#xff1a;
vuex是一个vue的状态管理工具#xff0c;状态就是数据。
大白话#xff1a;vuex是一个插件#xff0c;可以帮助我们管理vue通用的数据#xff08;多组件共享的…一、vuex概述
目标明确vuex是什么应用场景优势
1. 是什么
vuex是一个vue的状态管理工具状态就是数据。
大白话vuex是一个插件可以帮助我们管理vue通用的数据多组件共享的数据
2. 场景
①某个状态在很多个组件来使用个人信息
②多个组件共同维护一份数据购物车 3. 优势
①共同维护一份数据数据集中化管理
②响应式变化
③操作简洁vuex提供了一些辅助函数。 二、构建vuex[多组件数据共享]环境
目标基于脚手架创建项目构建vuex多组件数据共享环境 效果三个组件共享一份数据任意一个组件都可以修改数据三个组件的数据是同步的。 1. 创建项目“vuex-demo”
①勾选Babel、CSS Pre-processors、Linter / Formatter ②配置如下 ②创建一个空仓库
目标安装vuex插件初始化一个空仓库。 2. 核心概念 - state状态
目标明确如何给仓库提供数据如何使用仓库的数据
1. 提供数据
State提供唯一的公共数据源所有共享的数据都要统一放到Store中的State中存储。在state对象中可以添加我们要共享的数据。
// 创建仓库
const store new Vuex.Store({// state状态即数据类似于vue组件中的data// 区别// 1. data是组件自己的数据// 2. state是所有组件共享的数据state: {count: 101}
})
2. 使用数据
①通过store直接访问 // 获取store // (1) this.$store // (2) import 导入 store // 模板中 {{ $store.state.xxx }} // 组件逻辑中this.$store.state.xxx // JS模块中store.state.xxx ②通过辅助函数简化
mapState是辅助函数帮助我们把store中的数据自动映射到组件的计算属性中。 3. 核心概念 - mutations
目标明确vuex同样遵循单向数据流组件中不能直接修改仓库中的数据
错误写法this.$store.state.count
通过 strict: true 可以开启严格模式
1. 定义mutations对象对象中存放修改state的方法
const store new Vuex.Store({state: {count: 101},// 定义mutationsmutations: {// 第一个参数是当前store的state属性addCount(state) {state.count 1}}
})
2. 组件中提交调用mutations
this.$store.commit(addCount)
目标掌握mutations传参语法
提交mutation是可以传递参数的 this.$store.commit(xxx, 参数) 1. 提供mutations函数带参数 - 提交载荷payload
mutations: {...addCount (state, n) {state.count n}
},
2. 页面中提交调用mutation
this.$store.commit(addCount, 10) 目标实时输入实时更新巩固mutations传参语法 辅助函数mapMutations
目标掌握辅助函数mapMutations映射方法
mapMutations和mapState很像它是把位于mutations中的方法提取了出来映射到组件methods中。
mutations: {subCount (state, n) {state.count - n},
}
import { mapMutations } from vuexmethods: {...mapMutations([subCount])
}
this.subCount(10) // 调用 4. 核心概念 - actions
目标明确actions的基本语法处理异步操作。
需求一秒钟之后修改state的count成666。
说明mutations必须是同步的便于监测数据变化记录调试
1. 提供action方法
actions: {setAsyncCount (context, num) {// 一秒后给一个数去修改numsetTimeout(() {context.commit(changeCount, num)}, 1000)}
)
2. 页面中dispatch调用
this.$store.dispatch(setAsyncCount, 200) 辅助函数 - mapActions
目标掌握辅助函数mapActions映射方法
mapActions是把位于actions中的方法提取了出来映射到组件methods中
actions: {setAsyncCount (context, num) {// 一秒后给一个数去修改numsetTimeout(() {context.commit(changeCount, num)}, 1000)}
)
import { mapActions } from vuexmethods: {...mapActions([changeCountAction])
}
this.changeCountAction(666) // 调用 5. 核心概念 - getters
目标掌握核心概念getters的基本语法类似于计算属性
说明除了state之外有时我们还需要从state中派生出一些状态这些状态是依赖state此时会用到getters
例如state中定义了list为1-10的数组组件中需要显示所有大于5的数据
state: {list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
1. 定义getters
getters: {// 注意// (1) getters函数的第一个参数必须是state// (2) getters函数必须要有返回值filterList (state) {return state.list.filter(item item 5)}
}
2. 访问getters
方式①通过store访问getters
{{ $store.getters.filterList }}
方式②通过辅助函数mapGetters映射
computed: {...mapGetters([filterList])
},
{{ filterList }} // 使用 6. 核心概念 - 模块module进阶语法
目标掌握核心概念module模块的创建
由于vuex使用单一状态树应用的所有状态都会集中到一个比较大的对象。当应用变得非常复杂时store对象就有可能变得相当臃肿。当项目变得越来越大时Vuex会变得越来越难以维护 模块拆分 目标掌握模块中 state 的访问语法
尽管以及分模块了但其实子模块的状态还是会挂到根级别的state中属性名就是模块名
使用模块中的数据
①直接通过模块名访问 $store.state.模块名.xxx
②通过mapState映射
默认根级别的映射 mapState([xxx])子模块的映射 mapState(模块名, [xxx]) - 需要开启命名空间
export default {namespaced: true, // 开启命名空间state,mutations,actions,getters
} 目标掌握模块中 getters 的访问语法
使用模块中的getters中的数据
①直接通过模块名访问 $store.getters[模块名/xxx]
②通过mapGetters映射
默认根级别的映射 mapGetters([xxx])子模块的映射 mapGetters(模块名, [xxx]) - 需要开启命名空间 目标掌握模块中 mutation 的调用语法
注意默认模块中的mutation和actions会被挂载到全局需要开启命名空间才会挂载到子模块。
调用子模块中mutation
①直接通过store调用 $store.commit(模块名/xxx, 额外参数)
②通过mapMutations映射
默认根级别的映射 mapMutations([xxx])子模块的映射 mapMutations(模块名, [xxx]) - 需要开启命名空间 目标掌握模块中 action 的调用语法同理 - 直接类比 mutation 即可
注意默认模块中的mutation和actions会被挂载到全局需要开启命名空间才会挂载到子模块。
调用子模块中action
①直接通过store调用 $store.dispatch(模块名/xxx, 额外参数)
②通过mapActions映射
默认根级别的映射 mapActions([xxx])子模块的映射 mapActions(模块名, [xxx]) - 需要开启命名空间 示例代码
main.js
import Vue from vue
import App from ./App.vue
import store from /store/index
Vue.config.productionTip false// console.log(store.state.count)new Vue({render: h h(App),store
}).$mount(#app)App.vue
templatediv idapph1根组件- {{ title }}- {{ count }}/h1input :valuecount inputhandleInput typetextSon1/Son1hrSon2/Son2/div
/templatescript
import Son1 from ./components/Son1.vue
import Son2 from ./components/Son2.vue
import { mapState } from vuex
console.log(mapState([count, title]))export default {name: app,created () {// console.log(this.$router) // 没配// console.log(this.$store.state.count)},computed: {...mapState([count, title])},data: function () {return {}},methods: {handleInput (e) {// 1. 实时获取输入框的值const num e.target.value// 2. 提交mutation调用mutation函数this.$store.commit(changeCount, num)}},components: {Son1,Son2}
}
/scriptstyle
#app {width: 600px;margin: 20px auto;border: 3px solid #ccc;border-radius: 3px;padding: 10px;
}
/stylesrc/store/index.js
// 这里存放的就是vuex相关的核心代码
import Vue from vue
import Vuex from vuex
import user from ./modules/user
import setting from ./modules/setting// 插件安装
Vue.use(Vuex)// 创建仓库(空仓库)
const store new Vuex.Store({// 开启严格模式(有利于初学者检查不规范的代码 上线时需要移除消耗性能)strict: true,// 1. 通过state可以提供数据所有组件共享state: {title: 大标题,count: 100,list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]},// 2. 通过mutations 可以提供修改数据的方法mutations: {// 所有mutation函数第一个参数都是state// 注意点mutation参数有且只能有一个如果需要多个参数可以包装成一个对象或数组addCount (state, obj) {// 修改数据state.count obj.count},subCount (state, n) {state.count - n},changeCount (state, newCount) {state.count newCount},changeTitle (state, newTitle) {state.title newTitle}},// 3. actions 处理异步操作不能直接操作state还是需要commit mutationactions: {// context 上下文// context.commit(mutation名字, 额外参数)changeCountAction (context, num) {// 这里是setTimeout模拟异步以后大部分场景是发请求setTimeout(() {context.commit(changeCount, num)}, 1000)}},// 4. getters类似于计算属性getters: {// 注意点// 1. 形参第一个参数就是state// 2. 必须要有返回值返回值就是getters的值filterList (state) {return state.list.filter(item item 5)}},// 5. modules 模块modules: {user,setting}
})// 导出给main.js使用
export default storesrc/store/modules/setting.js
// setting模块
const state {theme: light, // 主题色desc: 测试demo
}
const mutations {setTheme (state, newTheme) {state.theme newTheme}
}
const actions {setThemeSecond (context, newTheme) {setTimeout(() {context.commit(setTheme, newTheme)}, 1000)}
}
const getters {}export default {namespaced: true,state,mutations,actions,getters
}src/store/modules/user.js
// user模块
const state {userInfo: {name: zs,age: 18},score: 80
}
const mutations {setUser (state, newUserInfo) {state.userInfo newUserInfo}
}
const actions {setUserSecond (context, newUserInfo) {// 将异步在action中进行封装setTimeout(() {// 调用mutation context上下文默认提交的就是自己模块的action和mutationcontext.commit(setUser, newUserInfo)}, 1000)}
}
const getters {// 分模块后state指代子模块的stateUpperCaseName (state) {return state.userInfo.name.toUpperCase()}
}export default {namespaced: true,state,mutations,actions,getters
}src/components/Son1.vue
templatediv classboxh2Son1 子组件/h2从vuex中获取的值: label{{ $store.state.count }}/labelbrbutton clickhandleAdd(1)值 1/buttonbutton clickhandleAdd(5)值 5/buttonbutton clickhandleAdd(10)值 10/buttonbutton clickhandleChange一秒后修改成666/buttonbutton clickchangeFn改标题/buttonhr!-- 计算属性getters --div{{ $store.state.list }}/divdiv{{ $store.getters.filterList }}/divhr!-- 测试访问模块中的state - 原生 --div{{ $store.state.user.userInfo.name }}/divbutton clickupdateUser更新个人信息/buttonbutton clickupdateUser2一秒后更新个人信息/buttondiv{{ $store.state.setting.theme }}/divbutton clickupdateTheme更新主题色/buttonbutton clickupdateTheme2一秒后更新主题色/buttonhr!-- 测试访问模块中的getters - 原生 --div{{ $store.getters[user/UpperCaseName] }}/div/div/templatescript
export default {name: Son1Com,created () {console.log(this.$store.getters)},methods: {updateUser () {// $store.commit(模块名/mutation名, 额外传参)this.$store.commit(user/setUser, {name: xiaowang,age: 25})},updateUser2 () {// 调用action dispatchthis.$store.dispatch(user/setUserSecond, {name: xiaohong,age: 28})},updateTheme () {this.$store.commit(setting/setTheme, pink)},updateTheme2 () {this.$store.dispatch(setting/setThemeSecond, blue)},handleAdd (n) {// 错误代码(vue默认不会监测监测需要成本)// this.$store.state.count// console.log(this.$store.state.count)// 应该通过 mutation 核心概念进行修改数据// 需要提交调用mutation// this.$store.commit(addCount)// console.log(n)// 调用带参数的mutation函数this.$store.commit(addCount, {count: n,msg: 哈哈})},changeFn () {this.$store.commit(changeTitle, 传智教育)},handleChange () {// 调用action// this.$store.dispatch(action名字, 额外参数)this.$store.dispatch(changeCountAction, 666)}}
}
/scriptstyle langcss scoped.box{border: 3px solid #ccc;width: 400px;padding: 10px;margin: 20px;}h2 {margin-top: 10px;}/stylesrc/components/Son2.vue
templatediv classboxh2Son2 子组件/h2从vuex中获取的值:label{{ count }}/labelbr /button clicksubCount(1)值 - 1/buttonbutton clicksubCount(5)值 - 5/buttonbutton clicksubCount(10)值 - 10/buttonbutton clickchangeCountAction(888)1秒后改成888/buttonbutton clickchangeTitle(前端程序员)改标题/buttonhrdiv{{ filterList }}/divhr!-- 访问模块中的state --div{{ user.userInfo.name }}/divdiv{{ setting.theme }}/divhr!-- 访问模块中的state --divuser模块的数据{{ userInfo }}/divbutton clicksetUser({ name: xiaoli, age: 80 })更新个人信息/buttonbutton clicksetUserSecond({ name: xiaoli, age: 80 })一秒后更新个人信息/buttondivsetting模块的数据{{ theme }} - {{ desc }}/divbutton clicksetTheme(skyblue)更新主题/buttonbutton clicksetThemeSecond(green)一秒后更新主题色/buttonhr!-- 访问模块中的getters --div{{ UpperCaseName }}/div/div/templatescript
import { mapState, mapMutations, mapActions, mapGetters } from vuex
export default {name: Son2Com,computed: {// mapState 和 mapGetters 都是映射属性...mapState([count, user, setting]),// 模块名 数据...mapState(user, [userInfo]),...mapState(setting, [theme, desc]),...mapGetters([filterList]),...mapGetters(user, [UpperCaseName])},methods: {// mapMutations 和 mapActions 都是映射方法// 全局级别的映射...mapMutations([subCount, changeTitle]),...mapActions([changeCountAction]),// 分模块的映射...mapMutations(setting, [setTheme]),...mapMutations(user, [setUser]),...mapActions(user, [setUserSecond]),...mapActions(setting, [setThemeSecond])// handleSub (n) {// this.subCount(n)// }}
}
/scriptstyle langcss scoped.box {border: 3px solid #ccc;width: 400px;padding: 10px;margin: 20px;}h2 {margin-top: 10px;}/style效果 三、综合案例 - 购物车
目标功能分析创建项目构建分析基本结构
1. 功能模块分析
①请求动态渲染购物车数据存vuex
②数字框控件 修改数据
③动态计算 总价和总数量
2. 脚手架新建项目注意勾选veux
vue create vue-cart-demo
③将原本src内容清空替换成素材的《vuex-cart-准备代码》并分析 目标构建cart购物车模块
说明既然明确数据要存vuex建议分模块存储购物车数据存cart模块将来还会有user模块article模块···
1. 新建store/modules/cart.js
export default {namespaced: true,state() {return {list: []}},
}
2. 挂载到vuex仓库上store/index.js
import cart from ./modules/cartconst store new Vuex.Store({modules: {cart}
})export default store 目标基于json-server工具准备后端接口服务环境
1. 安装全局工具 json-server 全局工具仅需要安装一次 [官网] yarn global add json-server 或 npm install json-server -g 2. 代码根目录新建一个db目录
3. 将资料index.json移入db目录
{cart: [{id: 100001,name: 低帮城市休闲户外鞋天然牛皮COOLMAX纤维,price: 128,count: 1,thumb: https://yanxuan-item.nosdn.127.net/3a56a913e687dc2279473e325ea770a9.jpg},{id: 100002,name: 网易味央黑猪猪肘330g*1袋,price: 39,count: 10,thumb: https://yanxuan-item.nosdn.127.net/d0a56474a8443cf6abd5afc539aa2476.jpg},{id: 100003,name: KENROLL男女简洁多彩一片式室外拖,price: 128,count: 2,thumb: https://yanxuan-item.nosdn.127.net/eb1556fcc59e2fd98d9b0bc201dd4409.jpg},{id: 100004,name: 云音乐定制IN系列intar民谣木吉他,price: 589,count: 1,thumb: https://yanxuan-item.nosdn.127.net/4d825431a3587edb63cb165166f8fc76.jpg}],friends: [{id: 1,name: zs,age: 18},{id: 2,name: ls,age: 19},{id: 3,name: ww,age: 20}]
}
4. 进入db目录执行命令启动后端接口服务
注意Node.js的版本要高于14.0.0低于14.0.0的可以重装Node.js [Node.js官网] json-server index.json 5. 访问接口测试 http://localhost:3000/cart 目标请求获取数据存入vuex映射渲染 目标修改数量功能完成
注意前端vuex数据 以及 后端数据库数据都要更新 目标底部getters统计
1. 提供getters
getters: {total (state) {return state.list.reduce((sum, item) sum item.count, 0)},totalPrice (state) {return state.list.reduce((sum, item) sum item.count * item.price, 0)}
}
2. 使用getters
computed: {...mapGetters(cart, [total, totalPrice])
} 所有代码
main.js
import Vue from vue
import App from ./App.vue
import store from ./storeVue.config.productionTip falsenew Vue({store,render: h h(App)
}).$mount(#app)App.vue
templatediv classapp-container!-- Header 区域 --cart-header/cart-header!-- 商品 Item 项组件 --cart-item v-foritem in list :keyitem.id :itemitem/cart-item!-- Foote 区域 --cart-footer/cart-footer/div
/templatescript
import CartHeader from /components/cart-header.vue
import CartFooter from /components/cart-footer.vue
import CartItem from /components/cart-item.vueimport { mapState } from vuexexport default {name: App,created () {this.$store.dispatch(cart/getList)},computed: {...mapState(cart, [list])},components: {CartHeader,CartFooter,CartItem}
}
/scriptstyle langless scoped
.app-container {padding: 50px 0;font-size: 14px;
}
/stylesrc/components/cart-header.vue
templatediv classheader-container购物车案例/div
/templatescript
export default {name: CartHeader
}
/scriptstyle langless scoped
.header-container {height: 50px;line-height: 50px;font-size: 16px;background-color: #42b983;text-align: center;color: white;position: fixed;top: 0;left: 0;width: 100%;z-index: 999;
}
/stylesrc/components/cart-item.vue
templatediv classgoods-container!-- 左侧图片区域 --div classleftimg :srcitem.thumb classavatar alt/div!-- 右侧商品区域 --div classright!-- 标题 --div classtitle{{ item.name }}/divdiv classinfo!-- 单价 --span classprice{{ item.price }}/spandiv classbtns!-- 按钮区域 --button classbtn btn-light clickbtnClick(-1)-/buttonspan classcount{{ item.count }}/spanbutton classbtn btn-light clickbtnClick(1)/button/div/div/div/div
/templatescript
export default {name: CartItem,methods: {btnClick (step) {const newCount this.item.count stepconst id this.item.idif (newCount 1) returnthis.$store.dispatch(cart/updateCountAsync, {id,newCount})}},props: {item: {type: Object,required: true}}
}
/scriptstyle langless scoped
.goods-container {display: flex;padding: 10px; .goods-container {border-top: 1px solid #f8f8f8;}.left {.avatar {width: 100px;height: 100px;}margin-right: 10px;}.right {display: flex;flex-direction: column;justify-content: space-between;flex: 1;.title {font-weight: bold;}.info {display: flex;justify-content: space-between;align-items: center;.price {color: red;font-weight: bold;}.btns {.count {display: inline-block;width: 30px;text-align: center;}}}}
}.custom-control-label::before,
.custom-control-label::after {top: 3.6rem;
}
/stylesrc/components/cart-footer.vue
templatediv classfooter-container!-- 中间的合计 --divspan共 {{ total }} 件商品合计/spanspan classprice{{ totalPrice }}/span/div!-- 右侧结算按钮 --button classbtn btn-success btn-settle结算/button/div
/templatescript
import { mapGetters } from vuex
export default {name: CartFooter,computed: {...mapGetters(cart, [total, totalPrice])}
}
/scriptstyle langless scoped
.footer-container {background-color: white;height: 50px;border-top: 1px solid #f8f8f8;display: flex;justify-content: flex-end;align-items: center;padding: 0 10px;position: fixed;bottom: 0;left: 0;width: 100%;z-index: 999;
}.price {color: red;font-size: 13px;font-weight: bold;margin-right: 10px;
}.btn-settle {height: 30px;min-width: 80px;margin-right: 20px;border-radius: 20px;background: #42b983;border: none;color: white;
}
/stylesrc/store/index.js
import Vue from vue
import Vuex from vuex
import cart from ./modules/cartVue.use(Vuex)export default new Vuex.Store({modules: {cart}
})src/modules/cart.js
import axios from axios
export default {namespaced: true,state () {return {// 购物车数据 [{}, {}]list: []}},mutations: {updateList (state, newList) {state.list newList},// obj: {id: xxx, newCount: xxx}updateCount (state, obj) {// console.log(obj)// 根据id找到对应的对象更新count属性即可const goods state.list.find(item item.id obj.id)goods.count obj.newCount}},actions: {// 请求方式get// 请求地址http://localhost:3000/cartasync getList (context) {const res await axios.get(http://localhost:3000/cart)// console.log(res)context.commit(updateList, res.data)},// 请求方式patch// 请求地址http://localhost:3000/cart/:id// 请求参数// {// name: 新值, [可选]// price: 新值, [可选]// count: 新值, [可选]// thumb: 新值, [可选]// }async updateCountAsync (context, obj) {// 将修改更新同步到后台服务器// console.log(obj)await axios.patch(http://localhost:3000/cart/${obj.id}, {count: obj.newCount})// 将修改更新同步到vuexcontext.commit(updateCount, {id: obj.id,newCount: obj.newCount})}},getters: {// 商品总数量total (state) {return state.list.reduce((sum, item) sum item.count, 0)},// 商品总价totalPrice (state) {return state.list.reduce((sum, item) sum item.count * item.price, 0)}}
}效果