setup选项 语法糖
//reactive: 接收一个对象类型的数据,返回一个响应式的对象' // import { reactive } from 'vue' // ref 接收简单类型或复杂类型 返回一个响应式的对象 // 本质:原有对象的基础上包了一层对象 包成了复杂类型 // 原理:包成复杂数据类型后 再借助reactive 实现响应式 // 1.脚本中访问数据 .value // 2.template 不需要.value (扒掉了一层)
计算属性
默认只读,也可以设置get,set
watch
// 1.监视单个数据的变化// watch(ref对象,(newValue,oldValue)=>{...})
watch(count,(newValue,oldValue)=>{
console.log(newValue,oldValue)
})// 2.监视多个数据的变化
// watch([ref对象1,ref对象2],(newArr,oldArr)=>{...})
watch([count,nikename],(newArr,oldArr)=>{
console.log(newArr,oldArr)
})
// 3.immediate 立即执行
// watch(count,(newValue,oldValue)=>{
// console.log(newValue,oldValue)
// },{
// immediate:true
// })
// 4.deep 深度监视 默认watch是浅层监视
// const ref1 = ref(简单类型) 直接监视
// const ref2 = ref(复杂类型) 监视不到复杂类型内部数据的变化
const userInfo = ref({
name:'张三',
age:18
})
const setUserInfo=()=>{
// 修改了userInfo.value修改了对象的地址.才能监视到
// userInfo.value = {name:'ls',age:10}
userInfo.value.age++
}
watch(userInfo,(newValue)=>{
console.log(newValue)
},{
deep:true
})
// 对于对象中的属性 精确监听
watch(()=>userInfo.value.age,(newValue,oldValue)=>{
console.log(newValue,oldValue)
})
父子通信
父传子
子传父
模版应用
provide和inject
传递provide('key','value' )接收inject('key')
defineOptions
defineOptions 宏。顾名思义,主要是用来定义 Options API 的选项。可以用 defineOptions 定义任意的选项, props, emits, expose, slots 除外(因为这些可以使用 defineXXX 来做到)
defineOptions({
name:'Foo',
//...更多自定义属性
})
defineModel
正常情况
使用defineModel
pinia
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const pinia = createPinia() //创建pinia实例
const app = createApp(App) //创建根实例
app.use(pinia) //pinia插件的安装配置
app.mount('#app') //视图的挂载
使用
在 Setup Store 中:
ref()
就是state
属性computed()
就是getters
function()
就是actions
异步操作
解构
使用storeToRefs函数可以辅助保持数据(state + getter)的响应式解构
<script setup>
import { storeToRefs } from 'pinia'
const store = useCounterStore()
//name
和doubleCount
都是响应式引用
// 下面的代码同样会提取那些来自插件的属性的响应式引用
// 但是会跳过所有的 action 或者非响应式(非 ref 或者 非 reactive)的属性
const { name, doubleCount } = storeToRefs(store)
// 名为 increment 的 action 可以被解构 方法直接解构
const { increment } = store
</script>
Pinia持久化插件
官方文档:https://prazdevs.github.io/pinia-plugin-persistedstate/zh/
安装插件 pinia-plugin-persistedstate
npm i pinia-plugin-persistedstate
使用 main.js
import persist from 'pinia-plugin-persistedstate'
...
app.use(createPinia().use(persist))
配置 store/counter.js
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'export const useCounterStore = defineStore('counter', () => {
...
return {
count,
doubleCount,
increment
}
}, {
persist: true
})
store第三个参数加入配置项
{
persist: {
key:'kis2-counter', //修改本地存储的唯一标识
storage:sessionStorage, //用什么存储
pick:['count'] //存储那些数据
}
<br/>
新盘新项目,不再等待,现在就是最佳上车机会!coinsrore.com
新车即将上线 真正的项目,期待你的参与