赞
踩
- import Vue from 'vue'
- import Vuex from 'vuex'
- import rs from './mutations/mm'
-
- Vue.use(Vuex)
- export default new Vuex.Store({
- // 全局状态
- state: {
- num: 22,
- user: {
- username: "张三",
- userage: 20,
- },
- list: []
- },
- // 计算属性
- getters: {
- xuAge(state) {
- return state.user.userage + 1
- }
-
-
- },
- // 修改数据,状态的方法
- mutations: {
- upAge(state, p) {
-
- console.log(p);
- this.state.user.userage++;
- this.state.num += p;
- },
- getContextList(state, payload) {
- state.list = payload
- },
- ...rs
-
-
-
- },
- // 异步修改数据方法
- actions: {
- getjoke(context) {
- let httpUrl = 'https://api.apiopen.top/getJoke?page=1&count=10&type=text'
- fetch(httpUrl).then((res) => {
- console.log(res);
- return res.json()
- }).then((res) => {
- console.log(res);
- // 不能直接修改 this.list = res.result(错误) 需要在mutations 中处理
- console.log("list:", res.result);
-
- context.commit('getContextList', res.result)
-
-
- })
-
- }
-
- },
- // vuex 细分模块
- modules: {
-
- }
- })
vx.vue
- <template>
- <div id="vx">
- <h1> vuex test</h1>
- <button @click="addage">add</button>
- {{ $store.state.user.userage }}
- num:{{ num }}
- <h1>{{ $store.getters.xuAge}}</h1>
-
- <ul v-for="(item,index) in $store.state.list" :key="index">
- {{ item.name}}
- <li>
- {{ item.text}}
- </li>
- </ul>
-
- </div>
- </template>
- <script>
- // 辅助函数
- import { mapState,mapMutations,mapGetters,mapActions} from 'Vuex'
-
- export default {
- mounted(){
- // dispatch 触发 actions 方法
- // this.$store.dispatch('getjoke')
- this.getjoke()
-
- },
- // 方法
- methods:{
- ...mapMutations(['upAge','getContextList']),
- ...mapActions(['getjoke']),
-
-
- addage(){
- console.log(this);
- // this.$store.commit('upAge',10) 提交到mutations upAge处理
- // commit 触发mutations 方法
- // this.$store.commit('upAge',10)
- this.upAge(2)
- }
-
- },
- // 计算属性
- computed:{
- ...mapGetters(['xuAge',]),
- ...mapState(['user','num'])
-
- }
-
-
- }
- </script>
- <style lang="scss">
- $width:375;
- @function vw($px){
- @return ($px/$width) * 100vw;
- }
-
- </style>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。