真正掌握vuex的使用方法(六)
生活随笔
收集整理的這篇文章主要介紹了
真正掌握vuex的使用方法(六)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
下面咱們來將切換的案例改為vuex來寫!?
首先需要在src目錄下,新建一個store文件夾,然后在該文件夾內創建一個store.js文件
main.js為:
import Vue from 'vue' import App from './App' import router from './router' import store from './vuex/store'//導入store.js Vue.config.productionTip = false new Vue({el: '#app',router,store,//添加store components: { App },template: '<App/>' })app.vue為:
<template> <div id="app"><!--對按鈕進行遍歷--><input type="button" v-for="(item,i) in tagList" :value="item.tagName" :class="{active:i==index}" @click="index=i"><!--對新聞進行遍歷--><div v-for="(item,i) in tagList" v-show="i==index"><p v-for="info in item.newList"><a :href="info.newHref">{{info.newTitle}}</a></p></div> </div> </template> <script>import axios from "axios";import {mapState} from "vuex";export default {name: 'App',data(){return {//index用于記錄當前所選按鈕的位置,值會根據點擊按鈕的不同而變化 index:0}},computed:{...mapState(["tagList"])},mounted(){axios.get("/static/tagList.json").then(data=>{this.$store.commit("SET_TAGLIST",data.data);})}} </script> <style>#app input,#app p{margin:5px;padding:5px;}#app input.active{background:red;}#app div{border:1px solid red;} </style>npm run dev,運行一次,一切正常!?
到目前為止,相信大家看以上的代碼應該都不會有太大問題了,所以不做解釋!?
咱們知道,對多個 state 的操作 , 使用 mutations 來操作比較好維護 , 但mutations 只可以寫一些同步操作,那異步操作放到哪里呢?比如咱們的axios放在哪里比較合適呢?在這個時候咱們就可以用到action了。通過action來操作mutations最終來改變state的值。?
接下來在store.js中添加actions:
那么接下來就要在App.vue中來觸發action下的方法getTagList:
import {mapState} from "vuex"; export default {name: 'App',data(){return {//index用于記錄當前所選按鈕的位置,值會根據點擊按鈕的不同而變化index:0}},computed:{...mapState(["tagList"])},mounted(){//使用 $store.dispatch('getTagList') 來觸發 action 中的 getTagList 方法。this.$store.dispatch("getTagList");} }使用 $store.dispatch(‘getTagList’) 來觸發 action 中的 getTagList 方法。也推薦大家在action里來寫一些異步方法!?
當然調用action的方法也有簡寫的形式:
npm run dev 運行,依舊完美!?
未完,待續!
轉載于:https://www.cnblogs.com/catbrother/p/9397411.html
總結
以上是生活随笔為你收集整理的真正掌握vuex的使用方法(六)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java常用API之DateFormat
- 下一篇: Vue.js学习笔记四