vue3(2)

pinia

语法:

import { defineStore } from "pinia";

export const useCountStore = defineStore('count', {
    state() {
        return {
            sum: 6
        }
    }
})

在相应的组件引入,取值

import {useCountStore} from '@/store/count'
    const countStore=useCountStore()
    console.log(countStore.sum);
    

修改数据(三种方式):

 //第一种方法
        // countStore.sum+=n.value
        //第二种方法
        // countStore.$patch({
        //     sum:888
        // })
        //第三种方法
  actions: {
        increatement(value: any) {
            this.sum += value
        }
    }       countStore.increatement(n.value)

storeToRefs:用于对pinia里面数据的响应式处理 const {sum,school,address}=storeToRefs(countStore)

ts配置文件位于store文件夹

getters配置项:

getters:{
    bigSum(state){
        return state.sum*10
    }
     upperSchool(state){
        return state.school.toUpperCase()
    }
}

$subscribe((mutate,state)={

//mutate是改变的信息 state是变化后的数据

})

组件通信:

props:有父有子

defineProps(['','']) 接收声明

// 声明接收props
	const props=defineProps(['car','sendToy'])
	props.sendToy(toy.value)
//父传值--sendToy为调用方法
<Child :car="car" :sendToy="getToy"/>
getToy(value){
  //value为儿传过来的值
}

自定义事件:

      <!--父组件 给子组件Child绑定事件 -->
  		<Child @send-toy="saveToy"/>
       // 子组件声明事件
        const emit=defineEmits(['haha'])
        //任意地点调用
        emit('haha')    //调用‘haha’
        emit('haha',值1)   //调用‘haha’,传值

mit:绑定事件(订阅),触发事件(发布)

all:拿到所有绑定事件 emit:触发事件 off:解绑事件 on:绑定某个事件

emitter.on(事件名,(值)=>{
  
})
    //触发事件
emitter.emit(事件名,值)

在组件卸载时解绑事件,防止内存泄漏

v-model:

    <AtguiguInput v-model="username"></AtguiguInput>
  //AtguiguInput
    <input 
    type="text" 
    :value="mima"
    @input="emit('update:mima',(<HTMLInputElement>$event.target).value)">

$attrs:祖->孙

v-bind="$attrs"

$refs用于 :**父→子

$parent用于:**子→父

$refs值为对象,包含所有被ref属性标识的DOM元素或组件实例。

$parent值为对象,当前组件的父组件实例对象

插槽:

默认插槽:

      父
        <Category title="今日热门游戏">
          <ul>
            <li v-for="g in games" :key="g.id">{{ g.name }}</li>
          </ul>
        </Category>
子
        <template>
          <div class="item">
            <h3>{{ title }}</h3>
            <!-- 默认插槽 -->
            <slot></slot>
          </div>
        </template>

具名插槽

  父    
        <Category title="今日热门游戏">
          <template v-slot:s1>
            <ul>
              <li v-for="g in games" :key="g.id">{{ g.name }}</li>
            </ul>
          </template>
          <template #s2>
            <a href="">更多</a>
          </template>
        </Category>
子
        <template>
          <div class="item">
            <h3>{{ title }}</h3>
            <slot name="s1"></slot>
            <slot name="s2"></slot>
          </div>
        </template>


vue3(2)
http://localhost:8090//archives/vuexia
作者
林丽专
发布于
2024年11月18日
许可协议