vue中使用vuex
2020-07-24 12:04
85 查看
vue中使用vuex (mutations)
一、适合初学者使用,保存数据以及获取数据
1、在store文件夹,新建个index.js文件(命名看个人习惯,如果没有该文件夹,可以新建一个,当然也可以不建文件夹,直接新建个js文件也是可以的)
在新建的js文件中写入如下代码:
import Vue from "vue" import Vuex from "vuex" Vue.use(Vuex); export default new Vuex.Store({ state:{ pathName: "", } mutations:{ // 保存当前菜单栏的路径 savePath(state,pathName){ state.pathName = pathName; }, } })
2、main.js引用:(注意路径即可)
// 引入vuex-store import store from './store/index'; new Vue({ el: '#app', router, store, render: h => h(App) })
3、在组件中保存数据:
methods:{ click(){ // 点击按钮进行一些操作,然后保存数据 this.$store.commit('saveCurrDbSource',this.db) } }
4、获取变量:(当数据初始获取不到时,可以使用计算属性用来获取)
this.$store.state.变量名 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。也就是说,前面两个都是状态值本身,mutations才是改变状态的执行者。 注意:mutations只能是同步地更改状态。
vue中使用vuex (actions)
Action 提交的是 mutation,而不是直接变更状态. Action 是异步的,mutation是同步的。
1.在store.js 中 代码为:
import Vue from 'vue' import Vuex from 'vuex' //使用vuex模块 Vue.use(Vuex); //声明静态常量为4 const state = { count : 4 }; const mutations = { add(state,n){ state.count +=n.a; }, sub(state){ state.count--; } }; const actions = { //2种书写方式 addplus(context){ //可以理解为代表了整个的context context.commit('add',{a:10}) }, subplus({commit}){ commit('sub'); } }; //导出一个模块 export default new Vuex.Store({ state, mutations, actions })
2.在组件中使用dispatch
template> <div id="app"> <div id="appaaa"> <h1>这是vuex的示例</h1> <p>组件内部count{{count}}</p> <p> <button @click = "addplus">+</button> <button @click = "subplus">-</button> </p> </p> </div> </div> </template> <script> export default { methods: { addplus(){ this.$store.dispatch("addplus");第一个参数为action里方法,第二个为要传的参数 }, subplus() { this.$store.dispatch("subplus") } } } </script>
高级映射写法
<template> <div id="app"> <div id="appaaa"> <h1>这是vuex的示例</h1> <p>组件内部count{{count}}</p> <p> <button @click = "addplus">+</button> <button @click = "subplus">-</button> </p> </p> </div> </div> </template> <script> //引入mapGetters import {mapState,mapMutations,mapGetters,mapActions} from 'vuex' export default { name:'app', data(){ return { } }, computed:{ ...mapState([ "count" 代替:this.$store.state.count; ]), }, methods:{ ...mapActions([ "addplus",// 将 `this.addplus()` 映射为 `this.$store.dispatch('addplus')` "subplus" ]) } } </script>
相关文章推荐
- vue项目vuex使用总结
- vue之mapMutaions的使用 && vuex中 action 用法示例 && api.js的使用
- Vue 兄弟组件通信的方法(不使用Vuex)
- 自定义vue全局组件use使用、vuex的使用详解
- Vue 中父子组件、兄弟组件通信(不使用Vuex)
- vue使用vuex控制全局组件
- vue-cli 中使用Vuex
- [Vue.js启航]——使用Vuex进行状态管理
- 在vue中使用vuex,修改state的值示例
- 在 vue-cli 中,使用VueX,并解决刷新state数据丢失问题
- 手摸手教你在vue-cli里面使用vuex,以及vuex简介
- vue.js的状态管理vuex中store的使用详解
- vue不使用vuex的前提下怎么进行非父子组件通信
- vuex在vue-cli和webpack构建的项目中的简单使用
- vue2.0之Vuex使用实例
- vue状态管理vuex使用之项目中如何合理引入vuex
- Vue-CLI与Vuex使用方法实例分析
- Vue中使用vuex,页面刷新登录状态不丢失,退出登录后清空登录状态的解决方法
- vue.js的状态管理vuex中store的使用
- vue学习 之 vuex安装及使用