轉: https://blog.csdn.net/lzh5997/article/details/80407518html
父子組件也能夠經過vuex的進行來進行中轉,其實vuex就相似與一個倉庫,父組件把東西放到倉庫,而後子組件,從倉庫裏面去出東西,由於子組件裏面是經過計算屬性來獲取的值(具備實時性),一旦父組件從新改變了數據,子組件就會從新從vuex裏面讀取數據vue
father.vuevuex
<template> <div> <h4>父組件</h4> <child></child> <button @click="transmitData">經過vuex給子組件傳值</button> </div> </template> <script> import Child from './child.vue' export default { components: { Child }, data() { return { testData: '我是父組件傳遞給子組件的值' } }, methods: { transmitData() { // 經過commit提交數據改變vuex裏面的數據 this.$store.commit('fatherData', this.testData) } } } </script> <style scoped> </style>
child.vuethis
<template> <div> <p v-if="_fatherData === null">暫無數據</p> <p v-else>{{_fatherData}}</p> </div> </template> <script> export default { computed:{ _fatherData(){ // 讀取store裏面的值 return this.$store.state.fatherDatas } } } </script> <style scoped> </style>
store.jsspa
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ // 初始化的數據 state: { fatherDatas: null }, // 改變state裏面的值得方法 mutations: { fatherData(state, data) { state.fatherDatas = data } } }) // 輸出模塊 export default store