[Vue] 5. 试试Vuex

一、以前写的demo

Vue-cli:4.2.3

demo地址:https://gitee.com/animalcoder/Vue

效果:维护监听List的内容(title,content ),显示到页面Son1 中,Son2 点提交,添加List

 

实现思路:

引入Vuex 依赖

     npm install xxxx -save ,import..........

新建store.js :   

    state:声明变量List (存标题与内容); mutations:声明增加方法Add()

Son2.Vue :

    data:声明变量title,content ;

    声明方法X(),X()里面调用store.js的增加方法Add(),将title,content数据插入List

    html的<input>用v-model双向绑定title content;

    提交按钮绑定调用方法X();

Son1.Vue:

    computed:动态监听List :新建方法 pageLists()返回store.js里面的List ;利用<li v-for> 显示

...
<li v-for="(item,idx) in pageLists" :key="idx" style="color:black;">
    ...
</li>  
...


import store from "@/store"; //取出存储器里面的lists
export default {
  name: "List",
  store,
  computed: {
    //动态监听变化
    pageLists: () => store.state.lists
  },
  ...
}

补上localStorage,使得关闭浏览器也能有数据

注意List  的localStorage存储方式    

取:xxx=JSON.parse(localStorage.getItem("list1"))

存:localStorage.setItem("list1",JSON.stringify(state.lists))

 

store.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

let defaultlist=[]
try {//
    if(localStorage.getItem("list1")){
        defaultlist=JSON.parse(localStorage.getItem("list1"))
    }
}catch(e){

}
export default new Vuex.Store({

    state:{//状态
        lists:defaultlist
    },
    mutations: {  //更改事件
        addItems (state , value){
            state.lists.push(value)
            localStorage.setItem("list1",JSON.stringify(state.lists))
        }
    },
    actions: {

    }
})

 


 

二、试试分模块的vuex

效果:

index.js是总的vuex,user.js是子模块

index.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

import user from './modules/user'


const store= new Vuex.Store({
    modules: {
        user:user
    },
    
})
export default store  //暴露变量到其他文件

user.js

const user={
    state:{
        username:'',
    },
    mutations:{
        SET_NAME:(state,name)=>{
            console.log("user set name"+name)
            state.username=name;
        }
    },
    getters:{
        name: state => state.user.name,
    }
}
export default user

在Test.vue使用vuex

注意,只有state才是分模块,commit的函数都是总的(不同模块的函数名不能重复),所以不能写成store.xxx.commit

直接store.commit

访问user的state的变量:store.state.user.username

<template>
  <div class="test">

      <input type='text' v-model="input1"/>
      <el-button  @click="summit()">提交</el-button>
      <p>gogogo{{title}}</p>

      
  </div>
</template>

<script>
import store from '../store/index'  //引入总vuex
export default {
  store,
  data() {
    return {
      title: "",
      input1:"",
    };
  },
  methods: {
    summit(){
        store.commit("SET_NAME",this.input1)
        this.title = store.state.user.username;
    }
  },
};
</script>

 


三、action初探

众所周知,变更状态的方法都写在mutations中

actions 提交的是 mutations,而不是直接变更状态。

actions 的用处是可以包含任意异步操作。

 

action的参数解构: 

actions里的xxx({commit},参数)看不懂系列

mutations: {
    increment1 (state) {
      state.count++
    }
},



actions: {
    increment (context) {
      context.commit('increment1')
    }
  }
等价于
actions: {
  increment ({ commit }) {
    commit('increment1')
  }
}

 

四、试试异步调用actions里的函数

 

在其他.vue

使用this.$store.dispatch('actions方法名',actions方法名的参数) 

 异步调用actions中的方法

.then()代表异步成功调用后才执行的逻辑

.catch()代表异步失败调用后才执行的逻辑

  methods: {
    getFuck() {},
    summit(){
        //store.commit("SET_NAME",this.input1)  同步调用

        //异步调用
         this.$store
            .dispatch('Login', this.input1)
            .then(() => {
              console.log("Login succ!")
              this.title = store.state.user.username;
              //this.$router.push({ path:  "/" });
            })
            .catch((error) => {
               console.log("???"+error)
            });
        //异步调用的过程中,会先调用下面的语句
          console.log("end")
    }
  },

 

在actions声明Login方法,axios.get()异步调用后端接口

代码解释:Login返回Promise对象,

if(成功){ 使用resolve(xxx)} 会返回到前面dispatch的.then()中, 这个xxx就是前面dispatch.then((xxx)=>{...})的xxx

if(失败{ 使用reject(xxx)} 会返回到前面dispatch的.catch()中,这个xxx就是前面dispatch.catch((xxx)=>{...})的xxx

 

当然,我们还要commit mutations中的方法来改变vuex中的状态,因为不要忘了actions 本身提交的是 mutations

 actions:{//用于$store.dispatch异步调用

     
        Login({ commit }, username) {  //login返回一个Promise对象  
            
            return new Promise((resolve, reject) => {//将登录axios异步处理,否则会拿不到数据
                axios.get('http://localhost:12177/login',{params:{'username':username}}).then(res => {//异步处理login后回调逻辑,更新姓名
                let res1=JSON.stringify(res.data)//对象转为json
                console.log("res="+res1)
                res1=JSON.parse(res1)//json串转为对象
                
                commit('SET_NAME', res1.data)//SET_TIME 是mutations中的方法
                
                resolve()  //表示promise已完成  resolve()中可加参数X代表Login成功的返回X
              })
              .catch(error => { //异常处理
                console.log("error:"+error)
                reject(error)
              })
            })
        },
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值