这篇文章主要介绍了vue父组件异步获取动态数据传递给子组件的问题。
vuex使用简介
使用vuex全局状态管理,其实就是利用vuex的辅助函数(mapState,mapMutations)
mapState是将state里面的数据映射到计算中(computed),mapMutations也是类似,把vuex中mutations的方法映射到组件里面,就可以在组件里面直接使用方法了,在vuex中使用异步(actions)去掉用接口,然后在接口成功的函数里面取触发同步(mutations)里面的方法,把得到数据传给mutations里面的方法里并且给state里面的属性赋值,然后就可以在子组件中使用computed计算中去获取数据并且渲染到页面上
vuex / index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| import Vue from 'vue' import Vuex from 'vuex' import axios from 'axios' Vue.use(Vuex) export default new Vuex.Store({ state: { title: '', list: [], isShow: false }, mutations: { changeListMutation(state, list) { state.list = list }, changeTitleMutation(state, title) { state.title = title }, toggleShow(state, isShow) { state.isShow = isShow } }, actions: { getListAction({ commit }) { axios.get('/mock/5afd9dc0c088691e06a6ab45/example/dataList') .then((res) => { commit('changeListMutation', res.data) }) .catch((error) => { console.log(error) })
} } })
|
子组件 list.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| <template> <div class="list"> <ul> <li v-for="(item,index) in list" :key="index" v-show="initShow" @click="changeTitle(item.title)">{{item.title}}</li> </ul> </div> </template>
<script> import {mapState,mapMutations} from 'vuex' export default { created(){ this.$store.dispatch('getListAction') }, computed:{ ...mapState({ list:'list', initShow:'isShow' }) }, methods:{ changeTitle(title){ this.$store.commit('changeTitleMutation',title) this.$store.commit('toggleShow',!this.initShow) } } } </script> // 触发异步里面的方法是用 this.$store.dispatch('这里是方法名') // 触发同步里面的方法是用 this.$store.commit('这里是方法名')
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| <template> <div class="inputBox"> <input type="text" readonly :value="getTitle" @click="toggleShow" placeholder="你喜欢什么"> </div> </template>
<script> export default { computed:{ getTitle(){ return this.$store.state.title }, initShow(){ return this.$store.state.isShow } }, methods:{ toggleShow(){ this.$store.commit('toggleShow',!this.initShow) } } } </script>
|