vue开发干货快速掌握vue

nodejs npm vue vuex快速安装使用入门腾讯课堂

2019-01-30  本文已影响30人  yichen_china

nodejs npm vue vuex快速安装使用入门腾讯课堂视频教程
https://ke.qq.com/webcourse/index.html#cid=369102&term_id=100439276&taid=2767200184541646&vid=g1420dhoxd5

vuex方法

1、数据设置 state
2、数据获取 getters #vue实例中 使用this.store.getter. 3、函数方法 mutations #vue实例中 使用this.store.commit('login',val);login函数写在mutation下
4、异步函数方法 actions #类似于 mutation 使用this.$store.dispatch('login',val);login函数写在Action下
5、模块Module

State实例
#store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
    state: {//设置状态写在这里
        hasLogin: false,//登陆状态
    },getters: {//获取状态写这里
                  login(state){
                        return  state.hasLogin;
                  }
        },mutations: {//同步方法写在这里
                  login: (state,payload) =>{
                state.hasLogin=payload;
        }
        },actions: {//异步方法写在这里
                  login:(context,payload) =>{
            setTimeout(function(){
                                //触发mutations 里的login方法
                context.commit("login",payload);
            },2000);
        }
        }
})

#index.vue
<div >
{{login}}
</div>
<div @tap="login(true)">
点击触发vuex里的函数
<div>
export default{
    computed:{
       login(){
            return this.$store.state.haslogin;
      }
    },methods:{
      login(val){
        this.$store.state.hasLogin=false; #设置值
        this.login=this.$store.getter.login(); #获取值
        this.$store.commit('login',val); #触发mutations内的方法,同步执行
        this.$store.dispatch('login',val); #触发actions内的方法,异步执行
    }
}

vuex 辅助方法快捷引入 ...map

在vue实例中可以使用三个点代替this.$store.getter快速引入vuex的方法
比如 ...mapGetters/...mapAction等;使用哪个就用import引入哪个

//现在
<div >
{{login}}
</div>
<div @tap="login(true)">
点击触发vuex里的函数
<div>
import {mapAction} from 'vuex'
export default{
    computed:{
        ...mapAction(["login","loginout"])
    },methods:{
      ...mapAction(["login","loginout"])
    }
}

如果浏览器报错,不支持...map,需要在vue项目中安装babel-preset-stage-2
cnpm install babel-preset-stage-2 --save-dev
然后 vue项目根目录的 .babelrc配置文件presets节点下增加["stage-2"]

上一篇 下一篇

猜你喜欢

热点阅读