使用vuex实现父组件调用子组件方法
生活随笔
收集整理的這篇文章主要介紹了
使用vuex实现父组件调用子组件方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
曲線救國。
核心原理就是父子共用一個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: 0list: []}},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了!
轉載于:https://www.cnblogs.com/flicat/p/8135875.html
總結
以上是生活随笔為你收集整理的使用vuex实现父组件调用子组件方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 记一次 javax.xml.soap.S
- 下一篇: html5倒计时秒杀怎么做,vue 设