Vue3.0——数据仓库配置、Vue2.0 和 Vue3.0差异(面试题)、副作用函数

目录

一、数据仓库配置

1.安装

2.写一个store文件

3.组件中的使用

4.修改数据

5.订阅修改

6.Getter 

7.Actions

8.模块化

二、Vue2.0 和 Vue3.0差异技术点——面试题

1、v-model

2、v-for绑定key

4、自定义事件绑定

5、v3提供v2中定义组件的方式

6、Vue3生命周期

1)  Vue2.x中的生命周期

2) Vue3.x的生命周期

3) vue3 新增的生命周期钩子

7、键码值

8、$on  $off  $once实例方法用不了

9、过滤器没有了

10、app.component注册全局组件

三、副作用函数


一、数据仓库配置

vuex

 vuex3.0适用于vue2.0

 vuex4.0适用于vue3.0和2.0

Pinia 适用于3.0 为了兼容2.0也能使用 主要是给3.0的组合式API设计的

官方中文网:  https://pinia.web3doc.top/

init-webpack  (vue3.0的环境)

1、vue create init

选择更多选择

Babel  router  linter  vuex

3.0

回车

lint on save不选

Pinia 是 Vue 的存储库,它允许您跨组件/页面共享状态。 如果您熟悉 Composition API,您可能会认为您已经可以通过一个简单的 export const state = reactive({}). 这对于单页应用程序来说是正确的,但如果它是服务器端呈现的,会使您的应用程序暴露于安全漏洞。 但即使在小型单页应用程序中,您也可以从使用 Pinia 中获得很多好处:

  • dev-tools 支持
    • 跟踪动作、突变的时间线
    • Store 出现在使用它们的组件中
    • time travel 和 更容易的调试
  • 热模块更换
    • 在不重新加载页面的情况下修改您的 Store
    • 在开发时保持任何现有状态
  • 插件:使用插件扩展 Pinia 功能
  • 为 JS 用户提供适当的 TypeScript 支持或 autocompletion
  • 服务器端渲染支持

1.安装

npm install pinia

2.写一个store文件

//  store/index.js文件
import { defineStore } from 'pinia'
//这里官网是单独导出  是可以写成默认导出的  官方的解释为大家一起约定仓库用use打头的单词 固定统一小仓库的名字不易混乱
const useStore = defineStore('storeId', {
  // 这里易错语法:如果箭头函数直接指向返回值的同学  记得把返回的对象用小括号括起来
  state: () => {
    return {
      msg: 'hello'
    }
  }
})

//main.js文件
import { createPinia } from 'pinia'
let app=createApp(App)
app.use(createPinia())

3.组件中的使用

<script setup>
	import useStore from "../store/index.js"
	let store=useStore()
	console.log(store,msg,111)	
</script>

4.修改数据

1)修改仓库状态1:  store.msg
有两种:store.msg  或者msg.value(引入ref)  (store是响应式的,msg不是,所以用ref就可以把msg变为相应的)

2)修改仓库状态2: store.$reset()     
store.$reset()     //将状态 重置 到其初始值

如果写了点击事件,让数据改变了,但是执行了store.$reset() ,就会回到原始的初始值

3)修改仓库状态3:   store.$patch   批量修改 ,也可以动态给仓库添加
store.$patch

//修改仓库状态1: 
//有两种:store.msg  或者msg.value(引入toRefs)  (store是响应式的,msg不是,所以用ref就可以把msg变为相应的)
<script setup>
	import useStore from "../store/index.js"
	let store=useStore()
    let fm=()=>{store.msg="666修改成功"}//store是一个响应性对象 因此可以修改并刷新
	let {msg}=store
	let fn=()=>{ msg="6666修改失败"} //解构之后修改是不行的,因为解构后msg为非响应式变量 同toRefs知识点
    
    //解决方案:利用toRefs把响应式对象的属性解构为响应性的变量
    import {toRefs} from "vue"
    import useStore from "../store/index.js"
	let store=useStore()
	let {msg}=toRefs(store)
	let fn=()=>{msg.value="6666修改成功啦"} //一定不要忘了value
</script>

//修改仓库状态2:
store.$reset()//将状态 重置 到其初始值


//修改仓库状态3:   批量修改
store.$patch({
  msg:"666修改成功",
  count:store.count+100,
})
store.$patch((state)=>{
    state.msg="666修改成功";
    state.count= state.count+100,
})
//问:$patch整体修改个单条修改的区别?
store.msg="666修改成功"
store.count=store.count+100
//答:状态刷新一次,可以批量修改

5.订阅修改

可以通过 store 的 $subscribe() 方法查看 状态及其变化,通过patch修改状态时就会触发一次

store.$subscribe((mutation, state) => { 
  // 每当它发生变化时,将整个状态持久化到本地存储
  localStorage.setItem('test', JSON.stringify(state))
})
<template>
  <div>
    <h1>page3</h1>
    <p>{{ store.count }}---{{ store.price }}</p>
    <button @click="change1">批量修改</button>
    <button @click="look">look</button>
  </div>
</template>
<script setup>
import { toRefs } from "vue";
import MyStore from "../store/user.js";
let store = MyStore();
store.$subscribe((n1, state) => {
  console.log("当仓库数据修改时就会运行", state);
});
console.log(store.count, store.price);
function change1() {
  //批量修改0
  // store.count++
  // store.price++
  let { count, price } = toRefs(store);
  count.value++;
  price.value++;

  //批量修改1
  // store.count++
  // store.price++

  //批量修改2
  store.$patch({
    count: 30,
    price: 200,
    n: 90,
  });

  //批量修改3
  // store.$patch(()=>{
  // 	store.count++
  // 	store.price++
  // })
}
function look() {
  console.log(store.n);  //unde
}
</script>
<style>
</style>

6.Getter 

Getter 完全等同于 Store 状态的 [计算值]

(https://v3.vuejs.org/guide/reactivity-computed-watchers.html#computed-values)。

它们可以用 `defineStore()` 中的 `getters` 属性定义。 他们接收“状态”作为第一个参数**以鼓励**箭头函数的使用:(ps:虽然鼓励但是依然提供了非es6玩家的使用方式 内部可以用this代表state)

如果它用到的变量没有变, 那就不会再次执行,跟计算属性一样。

//store/index.js文件
export const useStore = defineStore('main', {
  state: () => ({
    counter: 0,
  }),
  getters: {
    doubleCount: (state) => state.counter * 2,
  },
})

//组件中直接使用:  <p>Double count is {{ store.doubleCount }}</p>

7.Actions

在pinia中没有提供mutaion  因为Actions就够了(它可以异步同步的统一修改状态)

之所以提供这个功能 就是为了项目中的公共修改状态的业务统一

它也可以修改数据

1、可以异步函数的回调中修改仓库

2、可以统一修改

export const useStore = defineStore('main', {
  state: () => ({
    counter: 0,
  }),
  actions: {
    increment() {
      this.counter++//1.有this
    },
    randomizeCounter(state) {//2.有参数   想用哪个用哪个
      state.counter = Math.round(100 * Math.random())
    },
    randomizeCounter(state) {
        //异步函数
        axios("/test").then(res=>{
             state.counter = res.data.length
        })
     
    }
  },
})

//组件中的使用:
  setup() {
    const store = useStore()
    store.increment()
    store.randomizeCounter()
  }

8.模块化

一个文件一个小仓库,仓库之间可以相互访问数据  不同组件也可以访问任意小仓库数据

每一份js文件,都是一个仓库。

引入的时候仓库的名字不要重名了

//store/car.js文件
export const car = defineStore('car', {
  state: () => ({
    counter: 0,
  }),
  actions: {
   
  }
})

//store/userinfo.js文件
export const userinfo = defineStore('userinfo', {
  state: () => ({
    counter: 0,
  }),
  actions: {
     fn(state){state.counter=100}
  }
})



//A组件可以用car,userinfo两个仓库的数据
import {car} from "@/store/car.js"
import {userinfo} from "@/store/userinfo.js"
let store1=car()
store1.counter
let store2=userinfo()
store2.counter

//car仓库使用userinfo仓库跟组件一样的使用方式
//也可以把下面的代码写在Car里面
import {userinfo} from "@/store/userinfo.js"
let store2=userinfo()
store2.counter
store2.fn()

book.js

import { defineStore } from 'pinia'
export const useBook=defineStore("car",{
	state: () =>{
		return  {msg:"useBook仓库的数据",birth:"1997-02-03"}
	},
	getters:{
		age:(state)=>{
			return new Date().getFullYear()-new Date(state.birth).getFullYear()
		}
	},
	actions:{
		tool(){
			console.log(11111111)
			this.msg="66666"
			//1.可以异步函数的回调中修改仓库
			//2.统一修改
		}
	}
})

Page4.vue

<template>
	<div>
		<h1 @click="fn">p4</h1>
		<p>{{store.msg}}--{{store.birth}}---{{store.age}}</p>
	</div>
</template>
<script setup>
	import {useBook} from "../store/book.js"
	let store=useBook()
	console.log(store.age)
	let  fn=()=>{
		// store.msg="123"
		store.tool()
	}
</script>
<style>
</style>

二、Vue2.0 和 Vue3.0差异技术点——面试题

1、v-model

它重新设计了,组件中可以写多个v-mofel,然后后面加上修饰符:变量名进行双向绑定

2、v-for绑定key

v-for循环中可以不用绑定key,系统会自动绑定,如果要手动绑定,注意需要绑定唯一值。key也可以绑定在template上了,以前不可以。

3、v-if和v-for同时使用的话,v-if优先级更高,和vue2.0相反了

4、自定义事件绑定

自定义事件绑定的时候native修饰没有了,vue3.0希望自己去触发,

3.2之前在组合式API中必须引入definrEmit使用,3.2是defineEmits也可以不引入直接使用

选限售股hiAPI(3.3.3)直接使用this.$emit

5、v3提供v2中定义组件的方式

defineComponent

defineAsyncComponent 异步组件,用法就是在2.0的基础上,用这个函数处理之后的返回值

6、Vue3生命周期

1)  Vue2.x中的生命周期

beforeCreate   created
beforeMount    mounted
beforeUpdate  updated
beforeDestroy  destroyed
activated     deactivated   
errorCaptured 

2) Vue3.x的生命周期

在Vue3.x中,新增了一个setup生命周期函数,setup执行的时机是在beforeCreate生命函数之前执行,因为在这个函数中不能通过this来获取实例的;

同时为了命名的统一,

将beforeDestory改名为beforeUnmount,

destoryed改名为unmounted

beforeCreate(建议使用setup代替)created(建议使用setup代替)

选项式API
setup
beforeMount     mounted   
beforeUpdate    updated
beforeUnmount   unmounted

3) vue3 新增的生命周期钩子

我们可以通过在**生命周期函数**前加**on**来访问组件的生命周期

**Composition API 形式的生命周期钩子**

组合式API

onBeforeMount  onMounted   (unmounted==>app组件挂载了以后执行)
onBeforeUpdate  onUpdated
onBeforeUnmount  onUnmounted
onErrorCaptured
onRenderTracked
onRenderTriggered

effect

7、键码值

不能在事件修饰符中绑定键码值了 (比如:keyup),现在使用便准的key

8、$on  $off  $once实例方法用不了

用不了中央事件总线了

9、过滤器没有了

直接用函数实现过滤器技术

10、app.component注册全局组件

全局配置不再绑定到原型上,直接绑在globalProperties 

(网络工具不应该绑在原型上

所有组件都是共用的,不好。可以用this直接改,不好。

解决方案:用cdn引入)

三、副作用函数

let opt={
	  lazy: true
	  computed: true
	  scheduler?: (run: Function) => void
	  onTrack?: (event: DebuggerEvent) => void
	  onTrigger?: (event: DebuggerEvent) => void
	  onStop?: () => void
}
effect(()=>{
	console.log("start")
	return ()=>{console.log("clean")}
},opt)

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值