国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

詳解vuex 漸進(jìn)式教程實(shí)例代碼

2024-05-06 15:27:43
字體:
供稿:網(wǎng)友

vuex 漸進(jìn)式教程,從入門級(jí)帶你慢慢深入使用vuex。

Vuex 是什么?

Vuex 是一個(gè)專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲(chǔ)管理應(yīng)用的所有組件的狀態(tài), 并以相應(yīng) 的規(guī)則保證狀態(tài)以一種可預(yù)測的方式發(fā)生變化。

vuex官網(wǎng): vuex.vuejs.org/zh/guide/

安裝

安裝vue-cli:

cnpm install -g vue-cli vue init webpack vuex

安裝vuex

cnpm i vuex --save

1.初級(jí)使用方法

// main.jsimport Vue from 'vue'import App from './App'import router from './router'import Vuex from 'vuex' // 引入vuexVue.config.productionTip = falseVue.use(Vuex);let store = new Vuex.Store({ // store 對(duì)象 state:{  count:0 }})/* eslint-disable no-new */new Vue({ el: '#app', router, store, //使用store,這可以把 store 的實(shí)例注入所有的子組件 components: { App }, template: '<App/>'})

此時(shí)可以在組件中使用 this.$store.state.count 獲取store中state的值。如:

// 在組件的computed中使用 computed:{   count(){   return this.$store.state.count;   } }

想想一下當(dāng)項(xiàng)目比較大的時(shí)候數(shù)據(jù)繁瑣,如果按照上述方法使用vuex,當(dāng)你打開main.js你看的到場景是比較混亂的,各種數(shù)據(jù)繁雜在一起,不便于日后的維護(hù)。請(qǐng)看下一步:

2.中級(jí)使用方法: modules 模塊化

state用法

2.1 在main.js中刪除下述這部分代碼

let store = new Vuex.Store({ // store 對(duì)象 state:{  count:0 }})

2.2. 在src目錄下新建store文件夾并在該文件夾下新建index.js文件。 在 store/index.js寫入:

import Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex)const store = new Vuex.Store({ strict:true, // 開啟嚴(yán)格模式 確保state 中的數(shù)據(jù)只能 mutations 修改 state:{  count:0 }})export default store;

對(duì)應(yīng)的main.js應(yīng)該寫入:

import store from './store'

寫到這里,我們在組件里就可以獲取到store里的state的值了

2.3 為了方便測試直接在HelloWorld.vue 中使用store

<template> <div class="hello">  <h2>{{count}}</h2> </div></template><script>export default { name: 'HelloWorld', computed:{   count(){    return this.$store.state.count;   } }}</script>

很多時(shí)候咱們要對(duì)state里的值進(jìn)行操作,在vuex提供了一個(gè)方法mutations

mutations用法(使用mutations可以修改state的值)

在sore/index.js寫入:

//... state:{  count:0 }, mutations:{ // 更改數(shù)據(jù)的方法  add(state){   state.count++  },  //提交載荷用法//   add(state,n){ //   state.count += n//  },  sub(state){   state.count--  } }...//            
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 齐齐哈尔市| 长兴县| 武夷山市| 和林格尔县| 麻江县| 沧州市| 洛南县| 巴塘县| 尉氏县| 漠河县| 开阳县| 保亭| 定兴县| 酒泉市| 灌云县| 共和县| 嘉祥县| 特克斯县| 叙永县| 横山县| 兴国县| 新营市| 云霄县| 英超| 澄城县| 长岭县| 中阳县| 寿阳县| 灌阳县| 时尚| 桂平市| 威信县| 岐山县| 南陵县| 陆川县| 出国| 视频| 江门市| 东乡族自治县| 迁安市| 通河县|