vuex

作者: 黑夜的眸 | 来源:发表于2018-08-26 00:46 被阅读0次

    main.js

    const store = new Vuex.Store({
        //配置
    })
    
    new Vue({
        store:store,
        render: h => h(App),
    }).$mount('#app')
    

    注意Vuex.Store的Store S大写

    const store = new Vuex.Store({
        state:{
            count:0
        },
        mutations:{
            increase(state){
                state.count++
            },
            decrease(state){
                state.count--
            }
        },
    })
    

    state 存放初始状态值
    mutations 存放改变状态的函数

    users.vue

    <template>
        <div>
            <p>用户{{$route.params.id}}</p>
            <p>数量:{{num}}</p>
            <button @click="add">+1</button>
            <button @click="dec">-1</button>
        </div>
    </template>
    <script>
        export default{
            computed:{
                num(){
                    return this.$store.state.count
                },
            },
            mounted(){
                console.log(this.$route)
            },
            methods:{
                add(){
                    this.$store.commit('increase')
                },
                dec(){
                    this.$store.commit('decrease')
                },
            }
    
        }
    </script>
    
    • this.$store.state.count获取状态值
    • this.$store.commit('increase')调用改变状态的函数

    高级用法getters

    const store = new Vuex.Store({
        state:{
            list:[2,3,5,8,13,21]
        },
        getters:{
            filterList(state){
                return state.list.filter(item=>item >10)
            }
        }
    })
    
    //user.vue
    <template>
        <div>
            <p>{{filterList}}</p>
        </div>
    </template>
    <script>
        export default{
            computed:{
                filterList(){
                    return this.$store.getters.filterList
                }
            },
        }
    </script>
    

    this.$store.getters.filterList调用getters里的方法

    高级用法actions 操作异步

    相关文章

      网友评论

          本文标题:vuex

          本文链接:https://www.haomeiwen.com/subject/xgeniftx.html