位置: IT常识 - 正文

Vue笔记(五)vuex(vue笔记项目)

编辑:rootadmin
Vue笔记(五)vuex

目录

概念

搭建环境

基本使用(举例)

getters

四个map方法

模块化和命名空间


概念:

推荐整理分享Vue笔记(五)vuex(vue笔记项目),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:vue总结 笔记,vue3笔记,vue bi,vue详细教程,vue总结 笔记,vue笔记大全,vue笔记大全,vue笔记大全,内容如对您有帮助,希望把文章链接给更多的朋友!

在Vue中实现集中式状态(数据)管理的一个Vue插件,对vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信。

Github地址:https://github.com/vuejs/vuex

使用场景:多个组件依赖同一状态、来自不同组件的行为需要变更同一状态(多组件需要共享数据时)。

搭建环境:

因为vuex已经更新到4版本,而vue2与vuex3匹配,所以安装时运行npm i vuex@3

1.创建文件:

 index.js

// 此文件用于创建vuex中最核心的store// 引入核心库Vueimport Vue from 'vue';// 引入vueximport Vuex from 'vuex'// 应用vuex插件Vue.use(Vuex);// 准备actions,用于响应组件中的动作const actions={}// 准备mutations,用于操作数据(state)const mutations={}// 准备state,用于存储数据const state={}// 创建并暴露storeexport default new Vuex.Store({// const store = new Vuex.Store({    actions,// actions:actions,    mutations,// mutations:mutations,    state,// state:state,})// 暴露store// export default store;

2.在main.js中创建vm时传入store配置项

// 引入Vueimport Vue from 'vue';// 引入App组件import App from './App.vue';// 引入storeimport store from './store' // import store from './store/index.js'Vue.config.productionTip = false;new Vue({    el:'#app',    // 将App组件放入容器中    render:h=>h(App),    store,// store:store,})

为什么不能在main.js中import并use(vuex):

程序执行时会将import语句提升到最前面执行,读完import的东西才会接着读这个文件下面的内容;而程序必须先use(Vuex)再读store中的内容也就是main.js中的import store;所以采用如上写法,import和use(vuex)放在store中,就能保证程序先use(Vuex)再读store内其余内容。

基本使用(举例):

1.初始化数据

组件:.vue

<template>    <div>        <h1>当前求和:{{$store.state.sum}}</h1><br>        <select v-model="n">            <!-- value前加上":",引号里的值当成js表达式解析            如果不加,value里的值就会解析成字符串,做拼串操作 -->            <option :value="1">1</option>            <option :value="2">2</option>            <option :value="3">3</option>        </select>        <button @click="inc()">+</button>          <button @click="dec">-</button>          <button @click="oddInc">当前求和为奇数时加</button>          <button @click="waitInc">延迟3s加</button>    </div></template><script>export default {    name:'Search',    data() {        return {            n:1,        }    },    methods: {        inc(){            this.$store.commit('INC',this.n)        },        dec(){            this.$store.commit('DEC',this.n)        },        oddInc(){            this.$store.dispatch('oddInc',this.n)        },        waitInc(){            this.$store.dispatch('waitInc',this.n)        }    },}</script><style>select,button{    margin: 3px;}</style>

index.js

import Vue from 'vue';import Vuex from 'vuex'Vue.use(Vuex);// 准备actions,用于响应组件中的动作const actions={    // inc(context,value){    //     context.commit('INC',value)    // },    // dec(context,value){    //     context.commit('DEC',value)    // }, 这部分可以直接在组件中实现    oddInc(context,value){        if(context.state.sum%2)        context.commit('INC',value)    },    waitInc(context,value){        setTimeout(() => {            context.commit('INC',value)        }, 3000);    },}// 准备mutations,用于操作数据(state)const mutations={    INC(state,value){        state.sum+=value;    },    DEC(state,value){        state.sum-=value    }}// 准备state,用于存储数据const state={    sum:0,}// 创建并暴露storeexport default new Vuex.Store({    actions,    mutations,    state,})

2.组件中读取vuex中的数据:$store.state.sum

3.组件中修改vuex中的数据:$store.dispatch(‘action中的方法名’,数据)或$store.commit(‘mutation中的方法名’,数据)

4.若没有网络请求或其他业务逻辑,组件中也可以越过actions,即不写dispatch,直接编写commit

getters:

当state中的数据需要经过加工后再使用时,可以使用getters加工

在index.js中追加getters的配置:

... ...

// 准备getters,用于将state中的数据进行加工

const getters={

    bigSum(state){

        return state.sum*10

    }

}

// 创建并暴露store

export default new Vuex.Store({

    ... ... ,

Vue笔记(五)vuex(vue笔记项目)

    getters

})

组件中读取数据:

$store.getters.bigSum

四个map方法:

mapState方法:用于帮助我们映射state中的数据为计算属性。

mapGetters方法:用于帮助我们映射getters中的数据为计算属性。

mapActions方法:用于帮助我们生成与action对话的方法,即包含$store.dispatch(xxx)的函数。

mapMutations方法:用于帮助我们生成与mutations对话的方法,即包含$store.commit(xxx)的函数。

mapActions与mapMutations使用时,若要传递参数需要:在模板中绑定事件时传递好参数,否则参数是事件对象。

index.js

import Vue from 'vue';import Vuex from 'vuex'Vue.use(Vuex);// 准备actions,用于响应组件中的动作const actions={    oddInc(context,value){        if(context.state.sum%2)        context.commit('INC',value)    },    waitInc(context,value){        setTimeout(() => {            context.commit('INC',value)        }, 3000);    },}// 准备mutations,用于操作数据(state)const mutations={    INC(state,value){        state.sum+=value;    },    DEC(state,value){        state.sum-=value    }}// 准备state,用于存储数据const state={    sum:0,    name:'marling',    address:'枫林大街268号'}// 准备getters,用于将state中的数据进行加工const getters={    bigSum(state){        return state.sum*10    }}// 创建并暴露storeexport default new Vuex.Store({    actions,    mutations,    state,    getters})

.vue

<template>    <div>        <h1>当前求和:{{sum}}</h1>        <h2>当前求和*10:{{bigSum}}</h2>        <h3>姓名:{{name}},地址:{{address}}</h3>        <select v-model="n">            <option :value="1">1</option>            <option :value="2">2</option>            <option :value="3">3</option>        </select>        <button @click="INC(n)">+</button>          <button @click="dec(n)">-</button>          <button @click="oddInc(n)">当前求和为奇数时加</button>          <button @click="waitInc(n)">延迟3s加</button>    </div></template><script>import {mapGetters, mapState,mapMutations,mapActions} from 'vuex'export default {    name:'Search',    data() {        return {            n:1,        }    },    methods: {        // inc(){        //     this.$store.commit('INC',this.n)        // },        // dec(){        //     this.$store.commit('DEC',this.n)        // },        // 借助mapMutations生成对应的方法,方法中会调用commit去练习mutations(对象写法)        ...mapMutations({dec:'DEC'}),        // 借助mapMutations生成对应的方法,方法中会调用commit去练习mutations(数组写法)        ...mapMutations(['INC']),        // oddInc(){        //     this.$store.dispatch('oddInc',this.n)        // },        // waitInc(){        //     this.$store.dispatch('waitInc',this.n)        // }        // 借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(对象写法)        ...mapActions({oddInc:'oddInc'}),        // 借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(数组写法)        ...mapActions(['waitInc'])    },    computed:{        // sum(){        //     return this.$store.state.sum        // },        // name(){        //     return this.$store.state.name        // },        // address(){        //     return this.$store.state.address        // },        // 借助mapState生成计算属性,从state中读取数据(对象写法)        // "..."表示把每一项展开        // ...mapState({he:'sum',mingzi:'name',dizhi:'address'}),        // 借助mapState生成计算属性,从state中读取数据(数组写法)        ...mapState(['sum','name','address']),        // bigSum(){        //     return this.$store.getters.bigSum        // }        // 借助mapGetters生成计算属性,从state中读取数据(对象写法)        // ...mapGetters({bigSum:'bigSum'})        // 借助mapGetters生成计算属性,从state中读取数据(数组写法)        ...mapGetters(['bigSum'])    },    // mounted(){    //    const x=mapState({he:'sum',mingzi:'name',dizhi:'address'})    //     const x=mapState(['sum','name','address'])    // }}</script><style>select,button{    margin: 3px;}</style>

模块化和命名空间:

可以让代码更好维护,让多种数据分类更加明确。

store.js

const countAbout={ namespaced:true,//开启命名空间 state:{x=1}, mutations:{...}, actions:{...}, getters:{ bigSum(state){ return state.sum*10 } }}const personAbout={ namespaced:true,//开启命名空间 state:{x=1}, mutations:{...}, actions:{...},}const store=new Vuex.Store({ modules:{ countAbout, personAbout }})

开启命名空间后,组件中读取state数据:

//直接读取

this.$store.state.personAbout.list

//借助mapState读取

...mapState('countAbout',['sum','name','address'])

开启命名空间后,组件中读取getters数据:

//直接读取

this.$store.getters['personAbout/firstPersonName']

//借助mapGetters读取

...mapGetters('countAbout',[''bigSum])

开启命名空间后,组件中调用dispatch:

//直接dispatch

this.$store.dispatch('personAbout/addPersonWang',person)

//借助mapActions

...mapActions('countAbout',{oddInc:'oddInc',waitInc:'waitInc'})

开启命名空间后,组件中调用commit:

//直接commit

this.$store.commit('personAbout/ADD_PERSON',person)

//借助mapMutations

...mapMutation('countAbout',{inc:'INC',dec:'DEC'})

(视频:B站尚硅谷)

本文链接地址:https://www.jiuchutong.com/zhishi/297899.html 转载请保留说明!

上一篇:javascript - localStorage 本地存储(新增、删除、修改)使用教程

下一篇:基于梵·高《向日葵》的 图像阈值处理专题(二值处理、反二值处理、截断处理、自适应处理及Otsu方法)【Python-Open_CV系列(六)】(向梵高致敬油画)

  • 账本印花税的计税依据
  • 政府补助是否可以抵扣税
  • 非增值税应税项目可以抵扣进项税吗
  • 发票审核未通过,怎么查原因
  • 转租价格由谁决定
  • 先开票后跨月预缴税款可以吗
  • 公司买手表可以抵扣吗
  • 税收优惠退税会计处理
  • 递延收益影响当期损益吗
  • 没有抵扣的进项发票,开错了对方没有作废
  • 交易性金融资产和其他权益工具投资的区别
  • 赠与和继承哪个划算
  • 商业承兑汇票托收凭证怎么做分录
  • 净现金流量率计算公式
  • 车辆购置税过户流程
  • 新办企业地税要备案吗
  • 购进旅客运输服务为什么不能抵扣进项税额
  • 付工程款现金怎么做凭证?
  • 员工入职体检表格模板
  • 土地增值税清算报告
  • 当企业预收款项无需退回
  • 应交税费核算
  • 银行贷款入公账怎么入分录?
  • 一直零申报会怎么样
  • 鸿蒙的usb调试
  • 工商年报社保需要多少钱
  • 如何解决win7系统搜不到蓝牙耳机
  • 净现值法的优点包括
  • 收入税金账务处理
  • 森林植被恢复费标准
  • 收到股改代扣代缴税款
  • 民间非盈利组织会计信息的使用者
  • 微软汽车
  • php字符串型数据的定义方式
  • 如何选购餐桌椅
  • php system函数的用法
  • html页面间传数据
  • 微信小程序开挂方法
  • 苏尼亚尼
  • GCN经典论文笔记:Semi-Supervised Classification with Graph Convolutional Networks
  • 公允价值变动损益会计处理
  • 违约赔偿金要交税吗
  • 实际库存小于账面库存
  • 增值税一般纳税人
  • 对公账户名称可以是个人名字吗
  • 信息系统服务属于什么类
  • mysql版本5.5.x升级到5.6.x步骤分享
  • 公对私转账没有到账怎么查询
  • sqlserver监视器
  • 购买二手车后
  • 税务机关多收税款几年可以要求退回
  • 小规模减免税收入
  • 公司报税金额和实际发的不一致可以去告吗?
  • 进项税额已抵扣又红字冲红税务系统自动冲回吗
  • 汇算清缴要补交0.01怎么调成0
  • 什么是建账户
  • mysql5.5改密码
  • ubuntu zed
  • linux中安装telnet
  • lumia 925 win10
  • linux bye
  • win7系统玩红色警戒怎么全屏设置
  • windowsxp打不开网页怎么办
  • 新买的笔记本电脑需要做什么
  • python3.7内置模块
  • javascript:openattachment
  • 查看项目层级结构怎么查
  • python生成器send
  • python抓取数据代码
  • PYTHON内置函数,标准库,三方库的区别
  • 友盟模块
  • 谈心谈话记录由谁填写
  • 南京市国家税务局
  • 河北省国家税务总局云办税厅
  • 广东省电子税务局app下载手机版
  • 跨境电商出口商品结构
  • 美国对中国企业的政策
  • 地摊经济火了,月薪8000元
  • 代账好做吗
  • 股权转让是否要交土地增值税
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设