Vuex入门

目录

一、介绍

1、什么是Vuex?

2.vuex的各个js文件用途 

 二、使用

1.安装

2.创建store文件夹,创建文件

 3.在src/store/index.js中写入内容

4.在src/main.js中导入并使用store实例

5.在views新建vuex目录,添加Page1.vue和Page2.vue文件

6.配置路由

7.修改components/LeftNav.vue

 三、存取值

1.取值

state直接取值

getters取值

 2.存值

mutations存值

actions存值

3.发送ajax请求获取后台数据 


一、介绍

1、什么是Vuex?

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 +
库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化

2.vuex的各个js文件用途 

vuex一共有四个js文件组成分别是actions.jsgetters.jsmutations.jsstate.js

其中

  • State:单一状态树
  • Getters:状态获取
  • Mutations:触发同步事件
  • Actions:提交mutation,可以包含异步操作
  • Module:将vuex进行分模块

 二、使用

1.安装

npm i -S vuex@3.6.2

2.创建store文件夹,创建文件

如图所示:

 3.在src/store/index.js中写入内容

     新建vuex的store实例,并注册上面引入的各大模块

import Vue from "vue";
import Vuex from 'vuex'

import state from './state'
import getters from './getters'
import actions from './actions'
import mutations from './mutations'

Vue.use(Vuex)

const store = new Vuex.Store({
  state,
  getters,
  actions,
  mutations
})

export default store

4.在src/main.js中导入并使用store实例

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import axios from '@/api/http'
import VueAxios from 'vue-axios'
import router from './router'
import store from './store'

//开发环境下才会引入mockjs
process.env.MOCK && require('@/mock')

Vue.use(ElementUI);
Vue.use(VueAxios,axios)
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  data(){
    return{
      Bus: new Vue({})
    }
  },
  router,
  store,
  components: { App },
  template: '<App/>'
})

5.在views新建vuex目录,添加Page1.vue和Page2.vue文件

Page1.vue

<template>
  <div>
    <h1>这是页面1</h1>
  </div>
</template>

<script>
export default {
  name: "Page1"
}
</script>

<style scoped>

</style>

Page2.vue

<template>
  <div>
    <h1>这是页面2</h1>
  </div>
</template>

<script>
export default {
  name: "Page1"
}
</script>

<style scoped>

</style>

6.配置路由

修改src/router/index.js

import Page1 from '@/views/vuex/Page1'
import Page2 from '@/views/vuex/Page2'

#添加到与TopNav同级的地方
{
    path: '/vuex/Page1',
	name: 'Page1',
	component: Page1
},{
    path: '/vuex/Page2',
	name: 'Page2',
	component: Page2
}

7.修改components/LeftNav.vue

=====仅展示部分内容
<el-menu
    router :default-active="$route.path"
    default-active="2" class="el-menu-vertical-demo" background-color="#334157"
           text-color="#fff" active-text-color="#ffd04b" :collapse="collapsed">
    <!-- <el-menu default-active="2" :collapse="collapsed" collapse-transition router :default-active="$route.path" unique-opened class="el-menu-vertical-demo" background-color="#334157" text-color="#fff" active-text-color="#ffd04b"> -->
    <div class="logobox">
      <img class="logoimg" src="../assets/img/logo.png" alt="">
    </div>
    
    ///======添加的内容
    <el-menu-item
      index="/vuex/Page1"
      key="'key_999">
      <span>Vuex页面1</span>
    </el-menu-item>
    <el-menu-item
      index="/vuex/Page2"
      key="'key_1000">
      <span>Vuex页面2</span>
    </el-menu-item>

 

 三、存取值

  • 修改src/store/state.js
    export default {
      name: 'Vuex学习'
    }
    

1.取值

  • state直接取值

        修改src/views/vuex/Page1.vue的内容

<template>
  <div>
    <h1>这是页面1========{{msg}}</h1>
    <p>state直接取值</p>
    <button @click="func1">state直接取值</button>
  </div>
</template>

<script>
export default {
  name: "Page1",
  data(){
    return{
      msg: null
    }
  },
  methods:{
    func1(){
      this.msg = this.$store.state.name;
    }
  }
}
</script>

<style scoped>

</style>

 

  • getters取值

        1.修改src/store/getters.js中的值

export default {
  getName(state){
    return state.name;
  }
}

        2.修改Page1.vue的内容 

#div中添加
<p>getters取值</p>
<button @click="func2">getters取值</button>

#methods中添加
func2(){
	this.msg = this.$store.getters.getName;
}

       

 2.存值

  • mutations存值
  1. 修改mutations.js的内容
    export default {
      setName(state, payload) {
        state.name = payload.name;
      }
    }
    
  2. 修改Page1.vue
    #div中添加
    <p>mutations存值</p>
    <button @click="func3">mutations存值</button>
    
    #methdos中添加
    func3(){
    	this.$store.commit('setName',{
    		name: '这是修改后的Vuex学习'
    	});
    }
    
  3. 修改Page2.vue
    <template>
      <div>
        <h1>这是页面2===={{msg}}</h1>
      </div>
    </template>
    
    <script>
    export default {
      name: "Page2",
      data(){
        return{
          msg: null
        }
      },created() {
        this.msg = this.$store.state.name;
      }
    }
    </script>
    
    <style scoped>
    
    </style>
    

             

  • actions存值
  1. 修改Page1.vue的内容,删除data中的msg,改为computed属性
    computed:{
        msg(){
            return this.$store.state.name;
        }
    }
    
  2. 修改store/actions.js
    export default {
      setNameAsync(context, payload) {
        //context指的是vuex的实例
        //等价于this.$store
        setTimeout(function () {
          context.commit('setName',payload);
        },6000)
      }
    }
    
  3. 修改Page1.vue
    #div中添加
    <p>actions存值</p>
    <button @click="func4">actions存值</button>
    
    #methods中添加
    func4(){
    	this.$store.dispatch('setNameAsync',{
    		name: '这是修改后的Vuex学习--action'
    	});
    }
    

    效果:异步修改值202307291630

3.发送ajax请求获取后台数据 

  1. 修改api/action.js
    'VUEX_INFO': '/vuex/queryVuex',//vuex异步获取数据
    
  2. 修改Page1.vue
    #div中添加
    <p>后台ajax改变值</p>
    <button @click="func5">后台ajax改变值</button>
    
    #methods中添加
    func5(){
          this.$store.dispatch('setNameAjax',{
            _this: this
          });
        }
    
  3. 修改actions.js
    export default {
      setNameAsync(context, payload) {
        //context指的是vuex的实例
        //等价于this.$store
        setTimeout(function () {
          context.commit('setName', payload);
        }, 3000)
      },
      setNameAjax(context, payload) {
        let _this = payload._this;
        let url = _this.axios.urls.VUEX_INFO;
        let params = {
          resturantName: '这是ajax的修改'
        }
        _this.axios.get(url, {params}).then(resp=>{
          if(resp.data.success){
            context.commit('setName',{
              name: resp.data.msg
            })
          }
        }).catch(err=>{
    
        })
      }
    }
    

    202307291650

     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值