1. 程式人生 > >vuex環境搭建及小案例

vuex環境搭建及小案例

1、在專案下安裝vuex:npm install vuex --save-dev

2、在main.js中註冊vuex:

import Vuex from 'vuex'            //註冊vuex
import store from './vuex/store'   //某一值的初始狀態及改變方法

new Vue({
  el: '#app',
  router,
  store,                            //新增該項store
  components: { App },
  template: '<App/>'
})

3、搭建store.js

     

store.js的內容

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
    state: {
        age: '0' //儲存了一個公共狀態age
    },
    mutations : {
        showAge(state, msg){
            state.age= msg;
        }
    }
}) 
export default store

4、使用小案例

home.vue  (元件1)

<template>
    <div class="components1">
        <div>
            <input type="text" v-model="msg" />
            <input type="button" v-on:click="setName" value="設定" />
        </div>
    </div>
</template>

<script>
    export default {
        name: 'components1',
        data(){
            return {
                msg : ''
            }
        },
        methods : {
            setName(){
                this.$store.commit( 'showAge', this.msg ); //在元件1中修改元件3的狀態
            }
        }
    }
</script>

home1.vue(元件2)

<template>
    <div>
        <h3>看這裡,我在變化:{{myAge}}</h3>
    </div>
</template>
<script>
    export default {
        name : "components3",
        computed : {
 //一般會在元件的計算屬性(computed)獲取state的資料
//(因為,計算屬性會監控資料變化,一旦發生改變就會響應)
            myAge (){
                return this.$store.state.age;
            }
        }
    }
</script>

app.vue

<template>
  <div id="app">
  	<p>在輸入框裡面輸入值,後面的資料也會變化</p>
  	<home></home>
 //在元件2中渲染出元件1的值,並且在改變state中的age時,元件2中的元件1也會更新。
    <home1></home1>
    <img src="./assets/logo.png">
    <router-view/>
  </div>
</template>

<script>
import home from './components/home';
import home1 from './components/home1';
export default {
  name: 'app',
  components : {
    home,
    home1
  }
}	
</script>

5、效果圖