vue2 对应的 vuex、vue-router 都为3.
项目创建与框架安装
vue create hellovuex3
npm i vuex@3
npm install
npm run serve
vuex使用
vue集成vuex,数据更新&展示
- 新建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属性的方法
- 将vuex实例与vue实例进行绑定
import Vue from 'vue'
import App from './App.vue'
import store from "@/store";Vue.config.productionTip = falsenew Vue({store,render: h => h(App),
}).$mount('#app')
- 修改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存储数据不是持久化存储,刷新页面后,数据会消失。
- 处理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 += valuelocalStorage.setItem('score', state.score)}},modules: {}
})
export default store;
vuex数据的异步修改
vuex同步函数在mutations中进行定义,异步修改需要定义到actions.
mutations: {increment(state, value) {state.score += valuelocalStorage.setItem('score', state.score)},setScore(state, value) {state.score = valuelocalStorage.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. 用户管理、订单管理…, 这个时候分模块就显得很有必要了.
- 创建store/modules/user.js
const user = {state: {token: localStorage.getItem('token')},mutations: {setToken(state, token) {state.token = tokenlocalStorage.setItem('token', token)},},getters: {token(state) {return state.token.repeat(2)}},
}
export default user;
注意:
1.这里面的state写法与以往 state(){return{}}不同.
2.需要将数据类型进行导出
export default user;
- store/index.js 添加 modules属性
import user from "@/store/modules/user";
const store = new Vuex.Store({...modules: {user},
- 进行调用测试
mounted() {this.$store.commit('setToken', 'tokenxxx') //调用方法设置数据没有模块限定名console.error(this.$store.state.user.token) //state读取 , 前面添加module名限定console.error(this.$store.getters.token) //直接去掉了 module}
调用模块内的方法有些区别
- mutations、actions方法、getter不能携带module
- state要携带module
其他
- 国内github不稳定处理办法 测试采用配置 C:\Windows\System32\drivers\etc\hosts 域名和ip映射可行。
- package.json scripts 标签定义了 npm 、yarn可以执行的命令
- pakcage-lock.json 存储了npm install时框架依赖情况;yarn-lock.json 存储了 yarn install时框架依赖情况
-
npm i --legacy-peer-deps
// 使用 npm i --legacy-peer-deps 命令安装依赖时,会忽略 peer dependencies 的版本冲突问题。 - vue2 devtool chrome 插件下载
- 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,
})
- 视频推荐 - 30分钟学会Vue之VueRouter&Vuex