当前位置: 首页 > news >正文

vue复习91~135

1.空仓库

vuex的空仓库,写在store=>index.js里面
语法:new Vuex.store
最后在main.js中导入挂载

import Vue from 'vue'
import Vuex from 'vuex'
//插件安装
Vue.use(Vuex)
//创建仓库
export default new Vuex.Store()
//导出main.js使用
export default store
2.如何提供&访问vuex的数据
  1. 获取数据
    state:是唯一的公共数据源,在state数据中可以添加我们想要共享的数据
    而data是组件自己的数据
  2. 使用数据
    (1) 通过store直接访问
获取store:
1.this.$store
2.import 导入store模板中:{{ $store.state.xxx }}
组件逻辑中:this.$store.state.xxx
Js模块中: store.state.xxx

(2) 通过辅助函数
mapState,帮助把store里的数据 自动 映射到组件的 计算 属性中。

根组件
//导入,在js里面导
import { mapState } from 'vuex'//展开运算符
computed: {...mapState('cart', ['list'])}
3.核心概念-mutations

用于修改数据,严格模式,
上线时需要移除

const store = new Vuex.Store({//严格模式strict: true,state:{count:100}
})

state的数据修改只能通过mutations
mutations中存一系列方法,这些方法都是为了修改state

  1. 提供方法
    写在mutations中
  2. 页面调用
写在methods中
this.$store.commit(' 方法名 ')

传参
参数有且只能有一个,如果有多个参数,可以包装成一个对象传递
(1) 提供mutation函数,带参数

mutations: {...addCount(state,n) {state.count += n}
}

(2)页面中提交调用mutation

this.$store.commit('addCount', 10)
4.辅助函数mapMutations

映射方法
mapMutations跟mapState很像,它是把位于mutations中的方法提取了出来映射到组件methods中

//先导入
import { mapMutations } from 'vuex'
//在methods里映射
methods: {...mapMutations(['subCount'])handleSub(n){this.subCount(n)}
}
5.核心概念actions

处理异步操作

  1. 提供action方法
actions:{setAsyncCount(context, num) {//setTimeout模拟异步,以后大部分是发送请求setTimeout(()=>{context.commit('changeCount', num)}, 1000)}},
  1. 页面中dispatch调用
this.$store.dispatch(' setAsyncCount ',num)
6.辅助函数-mapActions

映射方法
mapActions是把actions里面的方法提取出来,映射到组件methods中

methods: {...mapActions(['changeCountAction'])}//调用this.changeCountAction(666)
7.核心概念-getters

getters是从state中派生一些状态,这些状态依赖state

// 4. getters 类似于计算属性getters: {// 注意点:// 1. 形参第一个参数,就是state// 2. 必须有返回值,返回值就是getters的值filterList (state) {return state.list.filter(item => item > 5)}},

getters和mapState的映射写在computed里
mapMutations和mapActions的映射写在methods里

8.核心概念-模块module
// 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
}
import user from './modules/user'//  modules 模块modules: {user,setting}
})

模块中访问state语法
使用模块中的数据:

  • 直接提供模块名访问$store.state.模块名.xxx
  • 提供mapState映射
    (1)默认根级别的映射mapState([’ '])
    (2)子模块的映射mapState(‘模块名’, [‘xxx’]) - 需要开启命名空间
namespaced: true

模块中访问getters语法

  • 通过模块名访问$store.getters([’ 模块名/xxx '])
  • 通过mapGetters映射
    (1)默认根级别的映射mapGetters([‘xxx’])
    (2)子模块的映射 mapGetters(‘模块名’,[‘xxx’]) - 需要开启命名空间

module中的mutation调用语法

注意:
默认模块中的mutation和actions需要开启命名空间,才会挂载到子模块

mutation调用:

  • 直接通过$store.commit(‘模块名/xxx’, 额外参数)
  • 通过mapMutations映射
    (1)默认根级别的映射mapMutations([‘xxx’])
    (2)子模块的映射 mapMutations(‘模块名’,[‘xxx’]) - 需要开启命名空间

module中的actions调用语法

actions调用:

  • 直接通过$store.dispatch(‘模块名/xxx’, 额外参数)
  • 通过mapActions映射
    (1)默认根级别的映射mapActions([‘xxx’])
    (2)子模块的映射 mapActions(‘模块名’,[‘xxx’]) - 需要开启命名空间

dispatch调action,action调mutation

<script>
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'])// handleSub (n) {//   this.subCount(n)// }}
}
</script>
9.综合案例-购物车
export default new Vuex.Store({// 提供数据state: {},// 提供与state相关的计算属性getters: {},// 提供方法,可以修改状态mutations: {},// 存放异步操作actions: {},// 分模块modules: {}
})

json-server 安装全局工具,准备后端接口

PS C:\Users\智奕然\Desktop\vue学习\vue-cart-demo\db> json-server --watch index.json
--watch/-w can be omitted, JSON Server 1+ watches for file changes by default
JSON Server started on PORT :3000
Press CTRL-C to stop
Watching index.json...( ˶ˆ ᗜ ˆ˵ )Index:
http://localhost:3000/Static files:
Serving ./public directory if it existsEndpoints:(接口)
http://localhost:3000/cart
http://localhost:3000/friends

异步放入action,基于mutation将数据传入state
module里面的代码

import axios from 'axios'
export default {namespaced: true,state () {return {list: []}},mutations: {updateList (state, newList) {state.list = newList},updateCount (state, obj) {const goods = state.list.find(item => item.id === obj.id)goods.count = obj.newCount}},// 异步用action做封装// created调用,actions发请求,mutation将数据存入vueactions: {async getList (context) {const res = await axios.get('http://localhost:3000/cart')context.commit('updateList', res.data)},// obj相当于传对象,即传两个及以上的参数时使用async updateAsync (context, obj) {// 修改更新同步到后台服务器await axios.patch(`http://localhost:3000/cart/${obj.id}`, {count: obj.newCount})// 将修改同步到前端vuexcontext.commit('updateCount', {id: obj.id,count: obj.newCount})}},getters: {// 累加,一律用reducetotal (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)}}
}
10.hm-shopping

api接口:发送ajax的请求接口模块
utils工具模块:自己封装的一些工具方法模块
yarn add vant@latest-v2
将px转化为vw进行适配,用postcss插件

相关文章:

  • GPU 架构入门笔记
  • 获得ecovadis徽章资格标准是什么?ecovadis评估失败的风险
  • 【ACL系列论文写作指北07-论文标题与关键词部分怎么写】-赢在第一眼
  • 今日行情明日机会——20250428
  • leetcode128-最长连续序列
  • 【默子AI】万字长文:MCP与A2A协议详解
  • 【学习笔记】RL4LLM(三)
  • BeeWorks企业内部即时通讯软件支持国产化,已在鸿蒙系统上稳定运行
  • 云原生--核心组件-容器篇-7-Docker私有镜像仓库--Harbor
  • Linux中的计划任务
  • 第1篇:Egg.js框架入门与项目初始化
  • go语言八股文(五)
  • el-Input输入数字自动转千分位进行展示
  • LeetCode 1482. 制作 m 束花所需的最少天数
  • 机器学习-入门-线性模型(2)
  • 【时间之外】软件管理如何避免人浮于事
  • Fiddler+Yakit实现手机流量抓包和小程序抓包
  • Nacos 3.0 上线 MCP Registry,支持 MCP 服务注册到发现全流程管理
  • Android平台Unity引擎的Mono JIT机制分析
  • Android WebRTC回声消除
  • 从咖啡节到话剧、演唱会,上海虹口“文旅商体展”联动促消费
  • 国家核准10台核电新机组,四大核电央企披露新项目进展
  • 广州一季度GDP为7532.51亿元,同比增长3%
  • 伊朗外长:美伊谈判进展良好,讨论了很多技术细节
  • 博物馆有一项活动40岁以上不能参加?馆方回应
  • 五矿地产:今年要确保债务“不爆雷”、交付“不烂尾”