119 lines
2.7 KiB
Markdown
119 lines
2.7 KiB
Markdown
|
#引入vuex状态机
|
||
|
在根目录创建store目录
|
||
|
|
||
|
#在main.js引入store、注册store、挂载store在程序上
|
||
|
import Vue from 'vue';
|
||
|
import App from './App';
|
||
|
#import store from './store'
|
||
|
#Vue.prototype.$store = store
|
||
|
|
||
|
const app = new Vue({
|
||
|
# store,
|
||
|
...App
|
||
|
})
|
||
|
app.$mount()
|
||
|
|
||
|
|
||
|
#在页面内使用store的属性
|
||
|
<view @tap="add"></view>
|
||
|
import { mapState,mapGetters,mapMutations } from 'vuex'//引入mapState
|
||
|
export default {
|
||
|
data() {
|
||
|
return {}
|
||
|
},
|
||
|
#单纯访问属性值
|
||
|
computed:{
|
||
|
tokenEv() {
|
||
|
return this.$store.state.token;
|
||
|
}
|
||
|
},
|
||
|
<!--
|
||
|
需要引入 import { mapState } from 'vuex'//引入mapState
|
||
|
-->
|
||
|
computed:mapState({
|
||
|
// 从state中拿到数据 箭头函数可使代码更简练
|
||
|
token: state => state.token,
|
||
|
}),
|
||
|
computed:mapState(['token']),
|
||
|
computed: {
|
||
|
...mapState({
|
||
|
token: function (state) {
|
||
|
return '追加的' + state.token
|
||
|
},
|
||
|
userInfo: state => state.userInfo,
|
||
|
})
|
||
|
},
|
||
|
computed:{
|
||
|
...mapState([
|
||
|
'token',
|
||
|
'userInfo',
|
||
|
'count',
|
||
|
'obj'
|
||
|
])
|
||
|
},
|
||
|
computed: {
|
||
|
...mapState({
|
||
|
token: state => state.moduleA.token,
|
||
|
count: state => state.moduleB.count
|
||
|
}),
|
||
|
},
|
||
|
#单纯访问方法
|
||
|
computed: {
|
||
|
todos() {
|
||
|
return this.$store.getters.doneTodos
|
||
|
}
|
||
|
},
|
||
|
computed: {
|
||
|
doneTodosCount() {
|
||
|
return this.$store.getters.doneTodosCount
|
||
|
}
|
||
|
},
|
||
|
<!-- 方法传值 -->
|
||
|
computed: {
|
||
|
getTodoById() {
|
||
|
return this.$store.getters.getTodoById(1)
|
||
|
}
|
||
|
},
|
||
|
<!--
|
||
|
需要引入 import { mapGetters } from 'vuex'//引入mapState
|
||
|
-->
|
||
|
computed: {
|
||
|
// 使用对象展开运算符将 getter 混入 computed 对象中
|
||
|
...mapGetters([
|
||
|
'doneTodos',
|
||
|
'doneTodosCount',
|
||
|
'getTodoById'
|
||
|
// ...
|
||
|
])
|
||
|
},
|
||
|
onLoad(options) {
|
||
|
#改变状态机里面的值
|
||
|
<!-- 传递字符串改变 -->
|
||
|
this.$store.commit('setToken', 'token已改变');
|
||
|
<!-- 传递对象 -->
|
||
|
this.$store.commit('updateUserInfo',{userInfo:'用户信息'})
|
||
|
this.$store.commit({
|
||
|
type: 'updateUserInfo',
|
||
|
userInfo: '新方式更新用户信息'
|
||
|
})
|
||
|
this.$store.commit('newProp',{c:'吃火锅'})
|
||
|
<!-- 输出值 -->
|
||
|
console.log(this.token);
|
||
|
<!-- 调用方法 -->
|
||
|
this.add();
|
||
|
<!-- 必须是同步方法 -->
|
||
|
this.$store.dispatch('addCountAction')
|
||
|
this.$store.dispatch('addCountAction2',{amount:10})
|
||
|
<!-- 异步方法 -->
|
||
|
this.$store.dispatch('addCountAction3',{amount:30})
|
||
|
setTimeout(()=>{
|
||
|
console.log(this.count,388);
|
||
|
},3000)
|
||
|
},
|
||
|
methods: {
|
||
|
<!--
|
||
|
需要引入 import { mapMutations } from 'vuex'//引入mapState
|
||
|
-->
|
||
|
...mapMutations(['add']),//对象展开运算符直接拿到add
|
||
|
}
|
||
|
}
|