vue3 学习入门
前提:vue3中,操作数据需要对象.value,template中直接用值,
js
```import {reaction } from " vue"
const state=reaction({
count=100
})
```js
- reaction函数:负责将接收的对象数据类型转化返回响应式对象
js
```import {ref } from " vue"
const state=ref({
count=100
})
```js
2.ref函数:负责将简单数据类型或对象数据类型转化返回响应式对象 在脚本中访问数据需要加.value,在template模板中不需要加 本质:在传入的数据之上,外层又包了一层对象
3.watch 监听一个或多个数据的变化:
js
监听单个数据变化:watch(count对象,(newvalue,oldvalue)=>{
},{
immediate:true ----一进页面就监听
},
{
deep:true------深度监视
})
js
监听多个数据变化:watch([count对象1,count对象1],(newarr,oldarr)=>{
})
js
监听某个特定的数据变化:watch(()=>对象.属性,(newvalue,oldvalue)=>{
})
4.父子通信 父传子 父组件中先导入子组件,在中写传入子组件的数据, 子组件由于加了setup,所以用defineprops宏,
go
```js
const props=defineProps({
属性名:类型
})
```
子传父
js
子组件:
const emit=defineEmits(['事件名1'])
const buy=()=>{
emit('事件名1',数据)
}
父组件:
定义父事件名1:
const 父事件名1=()=>{
对象.value=newvalue
}
父组件的子组件中:@事件名1='父事件名1'
5.在script setup中,组件内部的属性和方法是不开放给父组件访问的,可以通过defineExpress编译宏指定哪些属性和方法允许访问(暴露组件内的属性方法)
js
defineExpress({
属性名,
方法名
})
provide顶层组件向底层组件传递信息,inject底层组件接收来自顶层组件的信息
若是底层组件想改顶层组件传来的信息,顶层组件可以传递一个方法
js
顶层组件:
provide('changeCount',(newCount)=>{
count.value=newcount
})
底层接收:
const changeCount=inject('changeCount')
const clickFn=()=>{
changeCount(1000)
}
vue3.3及以上新特性,加入defineOptions宏,与setup平级,可以用defineOptions定义任意选项,props,emits,expose,slots除外,这些已经有了宏
js
defineOptions({
name:'afa'})
vue3.3及以上新特性,加入defineModel宏,与setup平级,可以用defineOptions定义任意选项,props,emits,expose,slots除外,这些已经有了宏
极大方便数据的双向绑定
js
子组件:
const modelValue=defineModel()
<div>
<input
type="text"
:value="modelValue"
@input="e=>modelValue=e.target.value"
>
</div>
父组件:
const txt=ref('123456')
<div>
<子组件名 v-model="txt"></子组件名>
{{ txt }}
</div>
pinia章节
使用vite创建空的vue3项目 npm create vue@latest
在store中定义pinia仓库
js
import {defineStore} from 'pinia'
import { ref,computed } from 'vue'
export const useCountStore= defineStore('count',()=>{
//声明数据state
const count=ref(0)
//操作数据方法action
const addCount=()=>count.value++
const subCount=()=>count.value--
//声明基于数据派生的计算属性getters(computed)
const double=computed(()=>count.value*2)
return{
count,
addCount,
subCount,
double
}
})
state getters actions
actions可同步可异步,下面介绍异步
js
import {defineStore} from 'pinia'
import { ref } from 'vue'
import axios from 'axios'
export const useCountStore= defineStore('count',()=>{
//声明数据state
const channelList=ref([])
//操作数据方法action
const getList=async()=>{
//返回数据解构
const {data:{data}} =await axios.get("地址")
channelList.value=data.返回数据的字段
}
return{
channelList,
getList
}
})
特别的,若导入到app.vue根组价pinia仓库数据进行了解构,会丢失响应式,此时可以用storeToRefs(),但方法可以直接解构,方法不需要响应式
pinia 持久化
js
npm i pinia-plugin-persistedstate
在main.js中进行导入:
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = createPinia()
app.use(pinia.use(piniaPluginPersistedstate))
注意:组合式,使用在你需要持久化的store文件的第三个参数,加上
{
persist: true,
},
如果想改名字:
{
persist:{
key:'mingzi',//修改本地存储的唯一标识
paths:['count']//选择你要存储的变量名
}
}