前言
提示:这里可以添加本文要记录的大概内容:
记录一下今日学习应用uniapp中的vuex
提示:以下是本篇文章正文内容,下面案例可供参考
一、vuex是什么?
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
按照自己理解来说就是公共数据管理模块。如果应用中数据量比较大的可以应用,不是很大的建议用缓存即可。
二、使用步骤
使用准备在项目中新建store目录,在该目录下新建index.js文件
1.引入
由于uniapp中内置了vuex,只需要规范引入即可:
// 页面路径:store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);//vue的插件机制
//Vuex.Store 构造器选项
const store = new Vuex.Store({
state:{
//存放状态
"username":"foo",
"age":18
}
})
export default store
// 页面路径:main.js
import Vue from 'vue'
import App from './App'
import store from './store'
Vue.prototype.$store = store
App.mpType = 'app'
// 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
const app = new Vue({
store,
...App
})
app.$mount()
2.state属性,主要功能为存储数据
第一种方法:通过属性访问,需要在根节点注入 store 。
<!-- 页面路径:pages/index/index.vue -->
<template>
<view>
<text>用户名:{
{
username}}</text>
</view>
</template>
<script>
import store from '@/store/index.js';//需要引入store
export default {
data() {
return {
}
},
computed: {
username() {
return store.state.username
}
}
}
</script>
第二种方法:在组件中使用,通过 this.$store 访问到 state 里的数据。
<!-- 页面路径:pages/index/index.vue -->
<template>
<view>
<text>用户名:{
{
username}}</text>
</view>
</template>
<script>
export default {
data() {
return {
}
},
computed: {
username() {
return this.$store.state.username
}
}
}
</script>
进阶方法:通过 mapState 辅助函数获取。当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余。 为了解决这个问题,我们可以使用 mapState 辅助函数 帮助我们生成计算属性,让你少按几次键,(说白了就是简写,不用一个一个去声明了,避免臃肿)
<!-- 页面路径:pages/index/index.vue -->
<template>
<view>
<view>用户名:{
{
username}}</view>
<view>年龄:{
{
age}}</view>
</view>
</template>
<script>
import {
mapState } from 'vuex'//引入mapState
export default {
data() {
return {
}
},
computed: mapState({
// 从state中拿到数据 箭头函数可使代码更简练(就是简写)
username: state => state.username,
age: state => state.age,
})
}
</script>
3. Getter属性,主要功能为计算筛选数据
可以认为是 store 的计算属性,对 state 的加工,是派生出来的数据。 就像 computed 计算属性一样,getter 返回的值会根据它的依赖被缓存起来,且只有当它的依赖值发生改变才会被重新计算。(重点,响应式数据的应用)
可以在多组件中共享 getter 函数,这样做还可以提高运行效率。
// 页面路径:store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
todos: [{
id: 1,
text: '我是内容一',
done: true
},
{
id: 2,
text: '我是内容二',
done: false
}
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
})
export default store
Getter属性接收传递参数,主要为:state, 如果在模块中定义则为模块的局部状态。getters, 等同于 store.getters。
// 页面路径:store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
todos: [{
id: 1,
text: '我是内容一',
done: true
},
{
id: 2,
text: '我是内容二',
done: false
}
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo