cnpm create vite
按照提示操作
安装less
cnpm add -D less
main.js
import "./css/index.less";
安装 cnpm install --save-dev less-loader less
可以
<style lang="less">
.orter{
color: salmon;
}
</style>
pinia
安装后
1.main.js 里面先注入
import {createPinia} from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist' //pinia数据持久化
const pinia = createPinia(); //实例化
pinia.use(piniaPluginPersist) //
const app = createApp(App);
app.use(Vant).use(pinia).mount('#app')
2.store文件夹下新建proudct.js文件
import {defineStore} from 'pinia'
import {getLists} from '../http/api'
export const productStore = defineStore('product',{
state:()=>({
products:[]
}),
actions:{
//异步请求,返回请求结果
getData(){
return new Promise((resolve,reject)=>{
getLists().then(res=>{
resolve(res)
}).catch(err=>{
reject(err)
})
})
},
//异步请求,直接赋值state状态
async getData2(){
const lists = await getLists().then(res=>res.data.data);
this.products = lists;
}
}
})
2vue文件应用
import {productStore} from '../store/product' //导入
import {storeToRefs} from 'pinia'
const store = productStore(); //实例化
const {products} = storeToRefs(store); //解构数据且数据是响应式
console.log(products)
defineProps({
msg: String
})
const count = ref(0)
async function qingqiu(){
await store.getData2();
console.log(products)
console.log(await store.getData2())
}
</script>
3.store文件夹下新建js文件
import {defineStore} from 'pinia'
export const basketStore = defineStore('basket',{
state:()=>({
basketItems:[]
}),
getters:{
getCount(state){
return state.basketItems.reduce((total,cur)=>total+cur.count,0)
}
},
actions:{
addItem(item){
//this.basketItems.push(item); //添加数据
if(this.basketItems.length>0){
let list = this.basketItems.filter(v=>v.product_id==item.product_id);
if(list.length>0){
list[0].count+=1;
return;
}else {
this.basketItems.push(item); //添加数据
}
}else {
this.basketItems.push(item); //添加数据
}
}
},
persist:{ //数据持久化
enabled:true
}
})
vue 文件应用
<script setup>
import {ref,defineProps} from 'vue'
import {basketStore} from '@/store/basket'
const store = basketStore();
const {products} = defineProps({
products:Array
})
function addProduct(v){
v.count = 1; //添加数量属性
store.addItem(v); //存储数据到pinia
}
</script>
网友评论