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

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"]

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容