曲线救国。
核心原理就是父子共用一个vuex对象,且看代码:
父组件parent.vue
<template> <div class="wrap"> <form action=""> <input type="text" v-model="searchParam.name"> <input type="text" v-model="searchParam.id"> <button @click="search"></button> </form> <child></child> </div> </template> <script> import store from '@/vuex'; export default { name: 'parent', store, components: { 'child': () => import('./child.vue'), }, data () { return this.$store.state.parent; }, methods: { search () { this.$store.dispatch('search'); } } }; </script> <style lang="less" scoped> </style>
子组件 child.vue
<template> <ul v-if="list && list.length"> <li class="river-item" v-for="item in list">{{item}}</li> </ul> </template> <script> export default { name: 'child', created () { this.$store.dispatch('getData'); }, data() { return this.$store.state.child; } }; </script> <style lang="less" scoped> </style>
vuex.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex); export default new Vuex.Store({ state: { parent: { searchParam: { name: '', id: '' } }, child: { pageIndex: 1, pageTotal: 0 list: [] } }, actions: { // 父组件的搜索方法 search({commit, dispatch, state}) { // 重置子组件的列表 state.child.pageIndex = 1; state.child.list = []; dispatch('getData'); } // 子组件的获取数据方法 getData ({commit, dispatch, state}) { fetch('http://test.com', { method: 'POST', // 使用父组件的参数(连传递props都省了 -_-!) body: state.parent.searchParam }).then(res => res.json()).then(data => { state.child.list = data; }); } } });
父组件和子组件的data及method都写到vuex里面去了,数据共享,这样父组件就可以调用vuex里面的action来修改子组件的data了!