vuex--一个菜鸟小白的学习笔记

2019-07-17  本文已影响0人  Yl奋斗的小白

Npm / cnpm install vuex --save安装vuex

Npm / cnpm install vuex-along@1.1.5 安装vuexalong防止刷新vuex变量值丢失 @1.1.5是版本号

首先在src目录下新建store(可自己定义文件夹名)文件夹里面建一个index.js文件

在main.js里引入并添加 store

Vuex由5部分组成: state、mutation、action、getter、module

State =>是用来定义变量的

Mutation =>定义方法   用来更改变量值(同步)

Action =>异步调用 mutation里的方法来修改变量值

Getter =>类似与 computed 属性

Modules =>模块化 vuex

Store下的index.js文件内容如下

以下面代码为例:

import Vue from 'vue'

import Vuex from "vuex"

import VuexAlong from "vuex-along"

import { app } from "./app"

Vue.use(Vuex)

export default new Vuex.Store({

    // 定义变量

    state: { 

        myname: ''

    },

    // 修改变量的方法

    mutations: { 

        setMyName(state,msg){

            state.myname = msg

        }

    },

    // 通过调用mutation的方法异步改变变量

    actions: { 

        setMyName(cxt, msg){

            cxt.commit("setMyName",msg)

        }

    },

    // “getter”(可以认为是 store 的计算属性)

    getters: {

        getMyName: state => {

            return state.myname

        }

    },

    // 引入外部的store

    modules: {

        app

    },

    // 引入 vuex-along 避免刷新后变量值还原

    plugins: [VuexAlong]

    }

)

State和mutation是必须的,其余可以看需求添加使用

this.$store.state.变量名  就可以在页面中获取对应变量的值

console.log(this.$store.state.myname,22)

调用mutation修改变量值: this.$store.commit(‘方法名’, ‘修改的值’)

this.$store.commit('setMyName','8')

当使用action异步修改state里的变量值时使用方法:

this.$store.dispatch(‘action里定义的方法名’,‘修改的值’)

this.$store.dispatch('setMyName',['567','222'])

使用getter获取state的变量值

this.$store.getter.getter里定义的方法

console.log(this.$store.getters.getMyName)

modules引入外部js时   这里引入的app.js

app.js代码如下

export const app = {

    state: {

        name: ''

    },

    mutations: {

        setName (state,msg) {

        state.name = msg

        }

    },

    actions: {

        setName (ctx, msg) {

        ctx.commit('setName', msg)

        }

    },

    getters: {

        getName: state => {

            return state.name

        }

    }

}

在页面中打印

console.log(this.$store)

console.log(this.$store.state)

说明引入外部定义的js后

action与getter和mutation和内部使用方法一样

但是state里取变量时

正常情况取变量值方法:this.$store.state.变量名

console.log(this.$store.state.myname)

app.js里因为时const app 所以取值时需要加 .app

console.log(this.$store.state.app.name)

请结合前面的store.js  和  app.js 代码看

上一篇 下一篇

猜你喜欢

热点阅读