vuex3入门

vue2 对应的 vuex、vue-router 都为3.

项目创建与框架安装

vue create hellovuex3

npm i vuex@3

npm install

npm run serve

请添加图片描述

vuex使用

vue集成vuex,数据更新&展示

  1. 新建store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        score: 0
    },
    mutations: {
        increment(state, value) {
            state.score += value
        }
    },
    modules: {}
})
export default store;


state 相当于普通组件data,读写数据的句柄。

mutations 相当于普通组件的methods, 封装同步修改state属性的方法

  1. 将vuex实例与vue实例进行绑定
import Vue from 'vue'
import App from './App.vue'
import store from "@/store";

Vue.config.productionTip = false

new Vue({
    store,
    render: h => h(App),
}).$mount('#app')

  1. 修改HelloWorld组件 展示和修改score
<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <div>score: {{ $store.state.score }}</div>
    <button @click="$store.commit('increment', 2)">score+2</button>
  </div>
</template>

访问数据 this.$store.state.score
函数调用 this.$store.commit(key,val)

请添加图片描述

存在的问题:vuex存储数据不是持久化存储,刷新页面后,数据会消失。

  1. 处理vuex处理刷新后数据消失问题
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        // score:0,
        score: localStorage.getItem('score') ? localStorage.getItem('score') : 0
    },
    mutations: {
        increment(state, value) {
            state.score += value
            localStorage.setItem('score', state.score)
        }
    },
    modules: {}
})
export default store;

vuex数据的异步修改

vuex同步函数在mutations中进行定义,异步修改需要定义到actions.

    mutations: {
        increment(state, value) {
            state.score += value
            localStorage.setItem('score', state.score)
        },
        setScore(state, value) {
            state.score = value
            localStorage.setItem('score', state.score)
        }
    },
    actions: {
        setDataAsync({commit}, value) {
            setTimeout(() => commit('setScore', value), 3000)
        }
    },
<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <div>score: {{ $store.state.score }}</div>
    <button @click="$store.commit('increment', 2)">score+2</button>
    <button @click="$store.dispatch('setDataAsync', 5)">异步修改score为5</button>

  </div>
</template>

异步函数调用 this.$store.dispatch(key,val);

计算属性getter

   getters: {
        computedScore(state) {
            console.error('computedScore is called')
            return state.score
        }
    },
    modules: {}
})

getter和computed功能上是一致,对计算结果进行缓存

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <div>score: {{ $store.state.score }}</div>
    <button @click="$store.commit('increment', 2)">score+2</button>
    <button @click="$store.dispatch('setDataAsync', 5)">异步修改score为5</button>
    <button @click=" score = $store.getters.computedScore">通过getter读取score {{ score }}</button>


  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {
      score: 0,
    }
  },

连续点击getter读取按钮, computedScore is called 只会执行一次; 只有当score变化之后,才会进行调用。
访问方式:this.$store.getters.computedScore

modules

上面的例子仅仅维护了一个字段score,生产环境碰到的会是多种类型的、eg. 用户管理、订单管理…, 这个时候分模块就显得很有必要了.

  1. 创建store/modules/user.js
const user = {
    state: {
        token: localStorage.getItem('token')
    },
    mutations: {
        setToken(state, token) {
            state.token = token
            localStorage.setItem('token', token)
        },
    },
    getters: {
        token(state) {
            return state.token.repeat(2)
        }
    },
}
export default user;

注意:

1.这里面的state写法与以往 state(){return{}}不同.

2.需要将数据类型进行导出 export default user;

  1. store/index.js 添加 modules属性
import user from "@/store/modules/user";
const store = new Vuex.Store({
    ...
    modules: {
        user
    },
  1. 进行调用测试
  mounted() {
    this.$store.commit('setToken', 'tokenxxx')  //调用方法设置数据没有模块限定名
    console.error(this.$store.state.user.token) //state读取 , 前面添加module名限定
    console.error(this.$store.getters.token) //直接去掉了 module
  }

调用模块内的方法有些区别

  1. mutations、actions方法、getter不能携带module
  2. state要携带module

其他

  1. 国内github不稳定处理办法 测试采用配置 C:\Windows\System32\drivers\etc\hosts 域名和ip映射可行。
  2. package.json scripts 标签定义了 npm 、yarn可以执行的命令
  3. pakcage-lock.json 存储了npm install时框架依赖情况;yarn-lock.json 存储了 yarn install时框架依赖情况
  4. npm i --legacy-peer-deps
    // 使用 npm i --legacy-peer-deps 命令安装依赖时,会忽略 peer dependencies 的版本冲突问题。

  5. vue2 devtool chrome 插件下载
  6. eslint 报错

根路径下创建.eslintrc.js文件,其内容如下:

module.exports = {
    'parser': '@babel/eslint-parser',  //支持ES6语法
    rules: {
        "*": "off"
    },
};

/vue.config.js 添加 lintOnSave:false

const {defineConfig} = require('@vue/cli-service')
module.exports = defineConfig({
    transpileDependencies: true,
    lintOnSave: false,
})
  1. 视频推荐 - 30分钟学会Vue之VueRouter&Vuex
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值