Vue3Pinia

1 篇文章 0 订阅

一、创建项目

npm create vite@latest
> cd <your-project-name>
> npm install
> npm run dev

二、下载pinia

npm i pinia

三、配置main .js

import { createApp } from 'vue'
import App from './App.vue'
//1.安装pinia npm install pinia
//2.导入pinia
import {createPinia} from 'pinia'
//3.挂载pinia
createApp(App).use(createPinia()).mount('#app')

四、配置store

4.1、在src目录下新建store文件夹,接着在store目录下新建index.js
4.2、配置index.js

//从pinia导入defineStore
import {defineStore} from 'pinia'

export default defineStore('main',{
    state:()=>{
        return {
            count:10,
            list:[{
                name:'mac',
                price:12000

            },
            {
                name:'macpro',
                price:16000
            }]
        }
    }
})

五、在App.vue进行操作修改state里面的数据

5.1、对count简单的++

<script setup lang="ts">
//导入store的模块
import useMainStore from './store/index.ts'
//使用这个store
const store =useMainStore()

function handelClick() {
  store.count++
}
</script>


<template>
<div>
  <h1>商品数量:{{store.count}}</h1>
  <button @click="handleClick">增加</button>
  </div>
</template>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

5.2、使用$patch 增加一个列表数据count+10

<script setup lang="ts">
//导入store的模块
import useMainStore from './store/index.ts'
//使用这个store
const store =useMainStore()
function  patchFnClick() {
  store.$patch((state)=>{
    state.count+=10;
    state.list.push({
       name:'华为',
      price:12000
    })
  })

}

</script>

<template>
<div>
  <h1>商品数量:{{store.count}}</h1>
  <ul> <li v-for='item in store.list'>{{item.name}}-----{{item.price}}</li></ul>
  <button @click="patchFnClick">+10</button>
  </div>
</template>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

5.3、使用$state替换原始state里面的数据

<script setup lang="ts">
//导入store的模块
import useMainStore from './store/index.ts'
//使用这个store
const store =useMainStore()


//使用$state替换原始state里面的数据
function toggelState() {
  store.$state={
    count:10000,
    list:[{
      name:'三星',
      price:1000000
    },
    {
      name:'三星',
      price:1000000
    },{
      name:'三星',
      price:1000000
    }]
  }
  
}

</script>

<template>
<div>
  <h1>商品数量:{{store.count}}</h1>
  <ul> <li v-for='item in store.list'>{{item.name}}-----{{item.price}}</li></ul>
  <button @click="toggelState">替换state</button>
  </div>
</template>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

5.4、重置state里面的数据

<script setup lang="ts">
//导入store的模块
import useMainStore from './store/index.ts'
//使用这个store
const store =useMainStore()

function resetClick() {
  store.$reset()
  
}
</script>

<template>
<div>
  <h1>商品数量:{{store.count}}</h1>
  <ul> <li v-for='item in store.list'>{{item.name}}-----{{item.price}}</li></ul>
  <button @click="resetClick">重置</button>
  </div>
</template>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

5.5、$subscribe监听整个仓库的变化(state)

//监听整个仓库的变化
//mutation 数据变化的信息
store.$subscribe((mutation,state)=>{
  console.log('mutations:',mutation);
  console.log('state:',state); 
})

请添加图片描述

六、getter

import { defineStore } from 'pinia'
import axios from 'axios'
export default defineStore('main', {

    state: () => {
        return {
            count: 10,
            list: [{
                name: 'mac',
                price: 12000,
                num: 1

            },
            {
                name: 'macpro',
                price: 16000,
                num: 1

            }]
        }
    },


    //计算总价 
    getters: {
        sumPrice: (state) => {
            return state.list.reduce((pre, item) => {
                return pre + (item.price * item.num)
            }, 0)

        }
    },


}

)
//app.vue
 <h1>商品总价:{{store.sumPrice}}</h1>

在这里插入图片描述

七、action

axios 异步请求数据

    state: () => {
        return {
            count: 10,
            //储存shopcart列表数据
            shopcat_list:[],
            list: [{
                name: 'mac',
                price: 12000,
                num: 1

            },
            {
                name: 'macpro',
                price: 16000,
                num: 1

            }]
        }
    }
 //同步异步都可以
    actions: {
        async getShopcart() {
            // let result = axios.get('https:wwww.cpngx.cn/static/timu/timu.json')
            let result = axios.get('https://www.escook.cn/api/cart')
            console.log((await result).data.list);
            this.shopcat_list=(await result).data.list

        }
    }

在这里插入图片描述

调用getShopcart()获取数据循环渲染页面

//app.vue
  <h1>商品列表</h1>
  <ul> 
   <li v-for='item in store.shopcat_list'>{{item.goods_name}}-----{{item.goods_price}}------{{item.goods_img}}</li>
  </ul>
  <button @click="store.getShopcart()">获取异步数据</button>

在这里插入图片描述

七、 完整代码

//App.vue

<script setup lang="ts">
//导入store的模块
import useMainStore from './store/index.ts'
//使用这个store
const store =useMainStore()

function handelClick() {
  store.count++
  
}

//增加一个列表数据
function  patchFnClick() {
  store.$patch((state)=>{
    state.count+=10;
    state.list.push({
       name:'华为',
      price:12000
    })
  })
  
}

//替换state里面的状态
function toggelState() {
  store.$state={
    // shopcat_list:[],
    count:10000,
    list:[{
      name:'三星',
      price:1000000,
      num:1
    },
    {
      name:'三星',
      price:1000000,
      num:1
    },{
      name:'三星',
      price:1000000,
      num:1
    }]
  }
  
}




//重置state
function resetClick() {
  store.$reset()
  
}

//监听整个仓库的变化
//mutation 数据变化的信息
store.$subscribe((mutation,state)=>{
  console.log('mutations:',mutation);
  console.log('state:',state); 
})
</script>

<template>
<div>
  <h1>商品总价:{{store.sumPrice}}</h1>
  <h1>商品数量:{{store.count}}</h1>
  <ul> 
    <li v-for='item in store.list'>{{item.name}}-----{{item.price}}</li>
  </ul>
  <button @click="handelClick">增加</button>
  <button @click="patchFnClick">+10</button>
  <button @click="toggelState">替换state</button>
  <button @click="resetClick">重置</button>
  <button @click="store.getShopcart()">获取异步数据</button>

  <h1>商品列表</h1>
  <ul> 
   <li v-for='item in store.shopcat_list'>{{item.goods_name}}-----{{item.goods_price}}------{{item.goods_img}}</li>
  </ul>
  </div>
</template>

<style>

#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

//index.js
import { defineStore } from 'pinia'
import axios from 'axios'
export default defineStore('main', {

    state: () => {
        return {
            count: 10,
            shopcat_list:[],
            list: [{
                name: 'mac',
                price: 12000,
                num: 1

            },
            {
                name: 'macpro',
                price: 16000,
                num: 1

            }]
        }
    },


    //计算总价 index.js 用store调用就行
    getters: {
        sumPrice: (state) => {
            return state.list.reduce((pre, item) => {
                return pre + (item.price * item.num)
            }, 0)

        }
    },


     //同步异步都可以
    actions: {
        async getShopcart() {
            // let result = axios.get('https:wwww.cpngx.cn/static/timu/timu.json')
            let result = axios.get('https://www.escook.cn/api/cart')
            console.log((await result).data.list);
            this.shopcat_list=(await result).data.list

        }
    }

}

)

八、效果展示!

请添加图片描述

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值