通過props 及 $emit在父子組件通訊,對應頻繁更新狀態考慮使用vuex
store.js
?
export default {// 存儲狀態值 state: {count: 0},// 狀態值的改變方法,操作狀態值// 提交mutations是更改Vuex狀態的唯一方法 mutations: {// 修改state,第一個參數就是state increment(state) {state.count++}} }
....
vuex如何異步修改狀態、?
父組件.vue
<template><div><child :message="changeMsg" @chageMsg="prent"></child><input type="button" value="父傳子" @click="changeMsga"><p>父組件文字:{{fromchildMsg1}}</p><p>count:{{ $store.state.count }}</p><input type="button" value="父組件按鈕Count++" @click="parentEvent"></div></template> <script>import child from '@/components/Home2'export default {data: function () {return {changeMsg: '1111111',childMsg: '',fromchildMsg1: ''}},methods: {parentEvent: function () {this.$store.commit('increment');},changeMsga: function () {this.changeMsg = '公司'},prent: function (msg) {this.fromchildMsg1 = msg;}},components: {child}}</script> <style scoped></style>
子組件.vue
<template><div>獲取值:<span>{{message}}</span><br><input type="button" value="子組件" @click="submitValue"><p>count:{{ $store.state.count }}</p><input type="button" value="子組件按鈕Count++" @click="childEvent"></div> </template> <script>export default {data: function () {return {}},props:['message'],methods: {childEvent: function(){this.$store.commit('increment')},submitValue: function(){this.$emit("chageMsg",'222222222222222');}}}</script> <style scoped></style>
初始化會看到,比較low的頁面
vue和vuex。
父子組件傳值,箭頭
父子組件狀態更改 ,點擊 (父子組件按鈕)會,發現 父子組件數組都在+1.
刷新頁面vuex數據丟失?
?
?針對刷新,狀態信息無,可以使用本地緩存localstorage
?