provide/inject
1.父组件
子组件
孙组件
数据是响应式的,一旦某个组件数据发生改变,另外引用的组件也会发生改变
总结:
vuex
首先安装vuex插件 npm install vuex
在store下面的index.js里
import {createStore} from "vuex"
export default createStore({
state:{
num:10,
sum:20
},
getters:{
total(state){
return state.num+state.sum
}
},
mutations:{
changeNum(state,val){
state.num=val
}
},
actions:{
changeBtn(){
alert('1')
}
}
})
在组件中调用修改等
<template>
<div>
<h1>这是A组件</h1>
{{num}}===>{{total}}
<button @click="btn">按钮</button>
<button @click='changeBtn'>按钮2</button>
</div>
</template>
<script setup>
import { computed } from "@vue/runtime-core"
import { useStore } from "vuex"
let store = useStore()
// let num = store.state.num //错的,这样的话修改不了vuex的值
let num =computed(()=>store.state.num)
console.log(store.state.num)
// let total = store.getters.total
let total =computed(()=>store.getters.total)
const btn =()=>{
store.commit('changeNum',800) //也可以传参,用val接收
}
const changeBtn =()=>{
store.dispatch('changeBtn')
}
</script>
<style scoped>
</style>
modules模块划分,和vue2写法一样
user.js里
export default{
state:{
userInfo:'info'
},
mutations:{
changeInfo(state){
state.userInfo="123"
}
}
}
index.js里
import {createStore} from "vuex"
import user from './modules/user'
export default createStore({
modules:{
user
},
})
引入vuex见上面写法
A组件
<template>
<div>
<h1>这是A组件</h1>
{{userInfo}}
<button @click="btn">按钮</button>
<button @click='changeBtn'>按钮2</button>
</div>
</template>
<script setup>
import { computed } from "@vue/runtime-core"
import { useStore } from "vuex"
let store = useStore()
// console.log(store.state.user.userInfo)
let userInfo = computed(()=>store.state.user.userInfo)
const btn =()=>{
store.commit('changeInfo')
}
</script>
<style scoped>
</style>
运用插件持久化存储
npm i vuex-persistedstate -S
在index.js里
import {createStore} from "vuex"
import persistedState from 'vuex-persistedstate'
import user from './modules/user'
export default createStore({
modules:{
user
},
plugins:[persistedState({
key:"xiaoyang",
paths:['user'] //需要存储的参数
})]
})