使用vuex实现父组件调用子组件方法
2017-12-28 15:18
429 查看
曲线救国。
核心原理就是父子共用一个vuex对象,且看代码:
父组件parent.vue
子组件 child.vue
vuex.js
父组件和子组件的data及method都写到vuex里面去了,数据共享,这样父组件就可以调用vuex里面的action来修改子组件的data了!
核心原理就是父子共用一个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了!
相关文章推荐
- 安卓四大组件之二#2-使用AIDL技术实现动态调用其他app中的Service的方法
- 使用rmi协议,基于cglib实现组件管理和远程方法调用
- [转]VC中使用ADO调用存储过程实现方法
- 使用Pmcmd远程调用Informatica技术实现方法
- 使用AjaxPro.Net框架实现在客户端调用服务端方法
- Asp.net中使用javaScript实现前后台方法的相互调用
- 使用RMI实现远程方法调用
- 使用MVC中的HtmlHelper对象的ActionLink方法,实现一个Javascript:void(0)效果,去调用一个JS方法
- 一种ACM评判内核简易实现 使用C# WEB调用C++编译器的方法
- 使用委托实现了在循环中调用不同的方法
- 在SQL Server中使用CLR调用.NET方法实现思路
- 在SQL Server中使用CLR调用.NET方法实现思路
- 使用Spring AOP前置通知实现提高方法调用的安全性能
- 使用C#反射实现用户控件调用父页面方法
- 零起点 Asp.net中使用javaScript实现前后台方法的相互调用
- 使用COM或者OLE的方法调用来控制Excel或者其他Office组件
- AJAXPRC实现了使用Javascript调用服务端方法
- [转]VC中使用ADO调用存储过程实现方法
- 使用Geoprocessor导出ArcSde中的数据,对COM 组件的调用返回了错误 HRESULT E_FAIL 的解决方法
- 使用IDispatch::Invoke函数在C++中调用C#实现的托管类库方法