Vue3基础、Pinia

71 阅读1分钟

子级向父级传递数据

  // 子级
   <button @click="$emit('increaseBy', '子级数据')">
        Increase by 1
    </button> 

// 父级
  <HelloWorld  @increaseBy="add" />
  const add = (d)=>{
    console.log(d); 
    num.value = d
 } 

安装 element-plus


npm install element-plus --save

Pinia

  1. 你可以认为 state 是 store 的数据 (data),getters 是 store 的计算属性 (computed), 而 actions 则是方法 (methods)。
  2. 在 Setup Store 中: ref() 就是 state 属性 computed() 就是 getters function() 就是 actions
store
// store/index.js
import { defineStore } from 'pinia'

export const useStore = defineStore('storeId', {
  // 为了完整类型推理,推荐使用箭头函数
  state: () => {
    return {
      // 所有这些属性都将自动推断出它们的类型
      count: 0,
      name: 'Eduardo',
      isAdmin: true,
      items: [],
      hasChanged: true,
    }
  },
})

// App.vue
import {useStore} from "./store/index"
// 可以在组件中的任意位置访问 `store` 变量 ✨  
const store = useStore() 
console.log(store.name);

actions
//App.vue
import { useStore } from '../store/index'
const store = useStore()  
<!--App.vue 调用 -->
<template>
  <button @click="store.setData()">获取数据/button>
</template>
// store /index.js
 state: () => ({
    count: 0,
    obj1:[]
  }), 
  actions:{
      setData(){
          let obj = ['香蕉','苹果','鸭梨']
          this.obj1 = obj
          return '成功'
      }
  }