日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > vue >内容正文

vue

对vuex的一点理解

發布時間:2024/4/17 vue 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 对vuex的一点理解 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

vuex是vue.js的一個狀態管理工具,它適用于解決平行組件之間的數據共享問題。一般情況下,我們更多的是父子組件之間通過props或$emit來實現傳值,如何不滿足以上情況那只有使用vuex進行解決。廢話不多說,直接上代碼。

1.先安裝vuex

npm install vuex --save

2.創建一個store的文件夾,新建store.js文件。我們需要在這個文件中引入Vue和Vuex,并且需要安裝Vuex

import Vue from 'vue'; import Vuex from 'vuex';Vue.use(Vuex);const state={count:1 }const mutations={add(state,n){state.count+=n;},reduce(state){if(state.count<=1){state.count=1;}else{state.count-=1; }} }export default new Vuex.Store({state,mutations})

State中放我們需要共享的數據,mutations是用來處理數據的方法。

3.創建視圖組件來調用store中的方法

<template><div><h2>{{msg}}</h2><hr/><h3>{{$store.state.count}}</h3><div><button @click="$store.commit('add',10)">+</button><button @click="$store.commit('reduce')">-</button></div></div> </template> <script>import store from "@/store/store"export default{data(){return{msg:'Hello Vuex'}},store,computed:{count(){return this.$store.state.count}}} </script> <style scoped></style>

 這樣一個簡單的vuex例子就完成了。

我們還可以有別的寫法來完成上述的功能

import Vue from 'vue'; import Vuex from 'vuex';Vue.use(Vuex);const state={count:1 }const mutations={add(state,n){state.count+=n;},reduce(state){if(state.count<=1){state.count=1;}else{state.count-=1; }} }const actions={"INC":(store)=>{store.commit('add',10)},"RED":(store)=>{store.commit('reduce')}} export default new Vuex.Store({state,mutationsactions })

  在store.js中定義一個actions用來負責把mutations中的邏輯發送給視圖

<template><div><h2>{{msg}}</h2><hr/><h3>{{$store.state.count}}</h3><div><button @click="add">+</button><button @click="reduce">-</button></div></div> </template> <script>import store from "@/store/store"export default{data(){return{msg:'Hello Vuex'}},store,computed:{count(){return this.$store.state.count}},methods:{add:function(){this.$store.dispatch("INC")},reduce:function(){this.$store.dispatch("RED")}}} </script> <style scoped></style>

  

 不足之處,希望多多指正~~

?

轉載于:https://www.cnblogs.com/linxing/p/8443862.html

總結

以上是生活随笔為你收集整理的对vuex的一点理解的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。