這個小示例是藉助另一個做者的示例稍加改動而來,相比原著增長了:getters、actions、mapStatehtml
目的是爲了更好的理解vuex的幾個核心屬性。感謝原做者。vue
大佬請跳過。文末附有另外一個做者的連接地址以及demo的下載地址。webpack
簡單補充幾點vuex 核心點git
npm i vue-cli -g
vue list
vue init webpack 項目名
cd 項目名
npm i
npm i vuex --save
npm run start
複製代碼
├── index.html
├── main.js
├── router
│ └── index.js
├── components
│ ├── parent.vue
│ └── child.vue
└── store
├── index.js # 咱們組裝模塊並導出 store 的地方
複製代碼
<template>
<div class="parent">
<h3>這裏是父組件</h3>
<button type="button" @click="clickHandler">修改本身文本</button>
<button type="button" @click="clickHandler2">修改子組件文本</button>
<div>Test: {{msg2}}</div>
<child></child>
</div>
</template>
<script>
/* eslint-disable */
import store from '../store'
import Child from './child.vue'
import {mapState} from 'vuex';
export default {
computed: {
...mapState({
msg2:state=>state.testMsg
})
//也能夠用這個獲取msg2
// msg2 () {
// return this.$store.getters.getMsg;
// }
},
methods:{
clickHandler(){
this.$store.dispatch('setMsg','李二狗本身')
},
clickHandler2(){
this.$store.dispatch('setMsg2','李二狗兒子')
}
},
components:{
'child': Child
},
store,
}
/* eslint-disable */
</script>
<style scoped>
.parent{
background-color: #00BBFF;
height: 400px;
}
</style>
複製代碼
<template>
<div class="child">
<h3>這裏是子組件</h3>
<div>childText: {{msg2}}</div>
<button type="button" @click="clickHandler">修改父組件文本</button>
<button type="button" @click="clickHandler2">修改本身文本</button>
</div>
</template>
<script>
/* eslint-disable */
import store from '../store'
import {mapState} from 'vuex';
export default {
name: "Child",
computed:{
// ...mapState({
// msg2:state=>state.childText
// })
msg2 () {
return this.$store.getters.getMsg2;
}
},
methods: {
clickHandler(){
this.$store.dispatch('setMsg','修改父組件')
},
clickHandler2(){
this.$store.dispatch('setMsg2','修改本身')
}
},
store
}
/* eslint-disable */
</script>
<style scoped>
.child{
background-color: palegreen;
border:1px solid black;
height:200px;
margin:10px;
}
</style>
複製代碼
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
/* eslint-disable */
const state = {
testMsg: '原始文本',
childText:"子組件原始文本"
}
const getters = {
getMsg (state) {
return state.testMsg
},
getMsg2 (state) {
return state.childText
}
}
const mutations = {
changeTestMsg(state, str){
state.testMsg = str;
},
changeChildText(state, str){
state.childText = str;
}
}
const actions = {
setMsg({commit, state}, str){
commit('changeTestMsg', str)
},
setMsg2({commit, state}, str){
commit('changeChildText', str)
}
}
const store = new Vuex.Store({
state: state,
getters:getters,
actions:actions,
mutations: mutations
})
/* eslint-disable */
export default store;
複製代碼
但願多一點入門分享示例,世界更美好。github
原著地址:傳送門web
demo下載地址:傳送門vuex
附上另外一個vuex核心講解地址:傳送門vue-cli
歡迎你們一塊兒交流學習,指出不對的地方。npm