寫在前面
本文旨在通過一個簡單的例子,練習vuex的幾個常用方法,使初學者以最快的速度跑起來一個vue + vuex的示例。
學習vuex需要你知道vue的一些基礎知識和用法。相信點開本文的同學都具備這個基礎。
另外對vuex已經比較熟悉的大佬可以忽略本文。
生成基於vue的專案
基於vue-cli腳手架生成一個vue專案 常用npm命令:
npm i vue-vli -g
vue --version
vue init webpack 專案名
複製程式碼
進入專案目錄,使用npm run dev先試著跑一下。
一般不會出現問題,試跑成功後,就可以寫我們的vuex程式了。
使用vue完成的示例
使用vuex首先得安裝vuex,命令:
npm i vuex --save
複製程式碼
介紹一下我們的超簡單Demo,一個父元件,一個子元件,父元件有一個資料,子元件有一個資料,想要將這兩個資料都放置到vuex的state中,然後父元件可以修改自己的和子元件的資料。子元件可以修改父元件和自己的資料。
先放效果圖,初始化效果如下:

如果想通過父元件觸發子元件的資料,就點“改變子元件文字”按鈕,點選後效果如下:

如果想通過子元件修改父元件的資料,就在子元件點選“修改父元件文字”按鈕,點選後效果如下:

程式碼檔案介紹
首先是Parent.vue元件
<template>
<div class="parent">
<h3>這裡是父元件</h3>
<button type="button" @click="clickHandler">修改自己文字</button>
<button type="button" @click="clickHandler2">修改子元件文字</button>
<div>Test: {{msg}}</div>
<child></child>
</div>
</template>
<script>
import store from '../vuex'
import Child from './Child.vue'
export default {
computed: {
msg(){
return store.state.testMsg;
}
},
methods:{
clickHandler(){
store.commit('changeTestMsg', '父元件修改自己後的文字')
},
clickHandler2(){
store.commit('changeChildText', '父元件修改子元件後的文字')
}
},
components:{
'child': Child
},
store,
}
</script>
<style scoped>
.parent{
background-color: #00BBFF;
height: 400px;
}
</style>
複製程式碼
下面是Child.vue子元件
<template>
<div class="child">
<h3>這裡是子元件</h3>
<div>childText: {{msg}}</div>
<button type="button" @click="clickHandler">修改父元件文字</button>
<button type="button" @click="clickHandler2">修改自己文字</button>
</div>
</template>
<script>
import store from '../vuex'
export default {
name: "Child",
computed:{
msg(){
return store.state.childText;
}
},
methods: {
clickHandler(){
store.commit("changeTestMsg", "子元件修改父元件後的文字");
},
clickHandler2(){
store.commit("changeChildText", "子元件修改自己後的文字");
}
},
store
}
</script>
<style scoped>
.child{
background-color: palegreen;
border:1px solid black;
height:200px;
margin:10px;
}
</style>
複製程式碼
最後是vuex的配置檔案
import Vue from 'vue'
import Vuex from 'vuex';
Vue.use(Vuex)
const state = {
testMsg: '原始文字',
childText:"子元件原始文字"
}
const mutations = {
changeTestMsg(state, str){
state.testMsg = str;
},
changeChildText(state, str){
state.childText = str;
}
}
const store = new Vuex.Store({
state: state,
mutations: mutations
})
export default store;
複製程式碼
後記
通過該vuex示例,瞭解vuex的常用配置及方法呼叫。希望對不怎麼熟悉vuex的同學快速上手vuex專案有點幫助。
因為沒太多東西,我自己也是剛接觸,本例就不往GitHub扔了,如果嘗試了本例,但是沒有跑起來的同學,可以一起交流下。
程式設計重在實踐,趕緊去跑一下吧。
關於本文
如果這篇文章使你有所收穫,不勝榮幸。 歡迎點贊,以期能幫助更多同學!