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

歡迎訪問 生活随笔!

生活随笔

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

vue

真正掌握vuex的使用方法(一)

發布時間:2024/4/17 vue 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 真正掌握vuex的使用方法(一) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

導語:vuex是什么?我的理解就是vuex是一個管理者,管理的方式是集中式管理,管理的對象即是vue.js應用程序中的眾多組件的共享部分。學習的過程當中,希望按照我的步驟一步一步來進行練習!

咱們知道,vue項目當中的父子組件的交互是單通道傳遞,父組件通過props向子組件傳遞參數,而在子組件當中不不能直接修改接收的參數,而是需要通過自定義事件的方式,例如:

<!-------------------------------------父組件---------------------------------> <template><div><a href="javascript:;" @click="show = true">點擊</a><t-dialog :show.sync="show"></t-dialog></div> </template><script> <template><div>{{isRed}}<children :isRed.sync="isRed"></children></div> </template> <script>import children from "@/components/children"export default {data() {return {isRed: false//向子組件傳遞默認值 }},components: {children}} </script> <!-------------------------------------子組件---------------------------------> <template><div><input type="button" :class="{active:isRed}" value="改變" @click="change"></div> </template> <script>export default {props:['isRed'],methods:{change(){//取反改變父組件的值this.$emit("update:isRed",!this.isRed);}}} </script> <style scoped>.active{background:red;} </style>

這樣是不是很麻煩?如果用vuex就會變的非常簡單!?
1、首先用npm包管理工具,安裝vuex

//因為這個包在生產環境中也要使用,所以在這里一定要加上 –save npm install vuex --save

2、然后在main.js當中引入vuex

import vuex from 'vuex'

3、使用vuex

Vue.use(vuex);//使用vuex //創建一個常量對象 const state={isRed:false } var store = new vuex.Store({//創建vuex中的store對象 state })

4、隨后在實例化Vue對象時,加入store對象:

new Vue({el: '#app',router,store,//使用storetemplate: '<App/>',components: { App } })

5、最后再將最初的示例修改為:

<!-------------------------------------父組件---------------------------------> <template><div>{{$store.state.isRed}}<children></children></div> </template> <script>import children from "@/components/children"export default {components: {children}} </script> <!-------------------------------------子組件---------------------------------> <template><div><input type="button" :class="{active:$store.state.isRed}" value="改變"@click="$store.state.isRed=!$store.state.isRed"></div> </template> <script>export default {} </script> <style scoped>.active{background:red;} </style>

到目前為止,這個示例就被簡化了很多??
前面將代碼都寫到了main.js中了,為了日后便于維護,更好的管理vuex,最好對vuex進行一些調整。?
1、在src文件夾根目錄創建vuex文件夾,然后在該文件夾內創建store.js文件。然后在文件內引入vue和vuex。

import Vue from 'vue'; import Vuex from 'vuex';

2、然后使用Vuex

Vue.use(Vuex );//使用Vuex //創建一個常量對象 const state={isRed:false } //讓外部引用vuex export default new Vuex.Store({//創建vuex中的store對象 state })

3、然后將main.js之前寫入的與vuex相關的內容清除掉,引入剛剛創建的store.js文件

import store from '@/vuex/store'

4、在實例化Vue對象時,加入引入的store對象:

new Vue({el: '#app',router,store,//使用storetemplate: '<App/>',components: { App } })

?

轉載于:https://www.cnblogs.com/catbrother/p/9397235.html

總結

以上是生活随笔為你收集整理的真正掌握vuex的使用方法(一)的全部內容,希望文章能夠幫你解決所遇到的問題。

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