Vuex应用状态管理

一个程序中有很多个页面,同时多个页面的很多数据也是共用的,所以我们要把这些共用页面抽离出来。这些数据就是用Vuex来进行管理。
首先,需要安装vuex依赖
在创建时选择手动配置:
在这里插入图片描述

选择路由和Vuex
在这里插入图片描述
安装完成后,项目中出现store/index.js文件

//放置全局状态
  state: {
    
    
  },
  //计算属性
  getter:{
    
    
  },
  //修改数据/状态的方法methods
  mutations: {
    
    
  },
  //异步修改数据
  actions: {
    
    
  },
  //vuex细分模块
  modules: {
    
    
  }

点击按钮增加年龄:

 //放置全局状态
  state: {
    
    
    username:"wangchen",
    age:17
  },
  //计算属性
  getters:{
    
    
  xuAge:function(state){
    
    
      return state.age + 1
    }
  },
  //修改数据/状态的方法methods
  mutations: {
    
    
    addAge(state,payload){
    
    
      state.age += payload
    }
  },
  //异步修改数据
  actions: {
    
    
  },
  //vuex细分模块
  modules: {
    
    
  }
<template>
  <div class="about">
    <h1>This is an about page</h1>
    <h1>姓名:{
    
    {
    
    $store.state.username}}</h1>
    <h1>年龄:{
    
    {
    
    $store.state.age}}</h1>
    <h2>虚岁:{
    
    {
    
    $store.getters.xuAge}}</h2>
    <button @click="addAge">添加</button>
  </div>
</template>

<script>
export default{
    
    
  mounted(){
    
    
      console.log(this); //打印查找如何获取组件
    },
    methods:{
    
    
      addAge:function(){
    
    
        this.$store.commit('addAge',3) //调用addAge方法,每次传入参数3
      }
    }
}

action请求异步数据并渲染在页面上:

//异步修改数据
  actions: {
    
    
    //去请求提供段子的服务器
    getJoke(context){
    
    
      let httpUrl = 'https://api.apiopen.top/getJoke?paga=1&count=10&type=text'
      fetch(httpUrl).then((res)=>{
    
       //第一次获取的是响应数据,是json结构,需要进行处理
          return res.json()
      }).then((res)=>{
    
    
        console.log(res)
        context.commit('getList',res.result)
      })
    }
  },

查找渲染元素:
在这里插入图片描述

<template>
  <div class="about">
    <ul>
      <li v-for="(item,i) in $store.state.list" :key="i">
          <h3>{
    
    {
    
    item.name}}</h3>
          <p>{
    
    {
    
    item.text}}</p>
      </li>
    </ul>
  </div>
</template>

<script>
export default{
    
    
  mounted(){
    
    
      console.log(this); 
      //触发vuex的action方法
      this.$store.dispatch('getJoke')
    },
}
</script>

猜你喜欢

转载自blog.csdn.net/sinat_33940108/article/details/113316234