欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

如何在Vue項(xiàng)目中使用vuex

 更新時(shí)間:2023年01月23日 11:52:10   作者:The..Fuir  
這篇文章主要介紹了如何在Vue項(xiàng)目中使用vuex問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

在Vue項(xiàng)目中使用vuex

在一個(gè)vue項(xiàng)目中使用vuex,需要根據(jù)項(xiàng)目來(lái)源分兩種情況 :

  • 第一種情況:在老項(xiàng)目中使用。 先額外安裝vuex包,然后在配置。
  • 第二種情況:在新項(xiàng)目中使用。 在配置vue-cli中創(chuàng)建項(xiàng)目時(shí),就可以直接選中vuex項(xiàng),這樣就不用做任何配置了(腳手架會(huì)自動(dòng)幫我們完成的)。

具體如下圖示:

這里我們主要說(shuō)明第一種情況,在一個(gè)老項(xiàng)目中如何使用vuex,步驟如下:

1.首先安裝vuex包,安裝完之后開(kāi)始配置

2.在src目錄下創(chuàng)建一個(gè)文件夾store,在store文件夾中新建一個(gè)index.js文件

3.創(chuàng)建Vuex.store實(shí)例 :index.js中進(jìn)行如下配置:

4.向Vue實(shí)例注入store:main.js中進(jìn)行如下配置: 

5.配置完后就可以在任意組件中使用了 

在任意組件中,通過(guò)this.$store.state 來(lái)獲取公共數(shù)據(jù),在模板中,則可以省略this而直接寫(xiě)成: {{$store.state.屬性名}}

一、安裝vuex

npm install vuex --save

二、創(chuàng)建store

在項(xiàng)目src目錄下創(chuàng)建store目錄,在store目錄中創(chuàng)建index.js文件。

寫(xiě)入一下內(nèi)容:

import Vue from 'vue'
import Vuex from 'vuex'
 
// 掛在Vuex
Vue.use(Vuex)
 
// 創(chuàng)建Vuex對(duì)象
const store = new Vuex.Store({
    state:{
        // 存放的鍵值對(duì)就是所要管理的狀態(tài)
        // 以key:value為例
        key : value,
    },
    mutations:{
        setKey(state, payload) {
            state.key = payload;
        }
    }
})
 
export default store

三、掛載store

在main.js中,添加代碼:

import store from './store'
 
new Vue({
  el: '#app',
  router,
  store: store, //store:store 和 router一樣,將我們創(chuàng)建的Vuex實(shí)例掛載到這個(gè)vue實(shí)例中
  components: { App },
  template: '<App/>'
})

四、在組件中使用

將需要使用的值寫(xiě)在computed中:

computed:{
? ? key() {
? ? ? ? return this.$store.state.key;
? ? }
}

如果在組件中使用v-model綁定computed中的值,需要在computed中定義set方法,如下:

computed:{
? ? key:{
? ? ? ? get(){
? ? ? ? ? ? return this.$store.state.key;
? ? ? ? },
? ? ? ? set(val){
? ? ? ? ? ? this.$store.commit('setKey', val);
? ? ? ? }
? ? }
}

五、在Vue組件中監(jiān)聽(tīng)Vuex

在Vue組件中監(jiān)聽(tīng)Vuex:

  • 通過(guò)computed獲取vuex中的狀態(tài)值。
  • 通過(guò)watch監(jiān)聽(tīng)值的改變。
computed:{
? ? key(){
? ? ? ? return this.$store.state.key;
? ? }
},
watch:{
? ? key(val) {
? ? ? ? // 要做的操作
? ? }
}

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論