记录一下使用vue2+pinia遇到的问题!
首先:
就是配置文件了本来使用的是v2发现v2不太兼容pinia需要安装另外一个插件@vue/composition-api
于是决定升级vue版本v2.6升级到v2.7,升级成功后直接安装
yarn add pinia
# 或者使用 npm
npm install pinia
这里推荐一下官网:https://pinia.vuejs.org/zh/getting-started.html
一下是我的配置文件有些文件需要一起升级只升级vue版本会报错!
{
"name": "xblr-vote-web",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build"
},
"dependencies": {
"axios": "^1.3.2",
"cookie": "^0.5.0",
"core-js": "^3.6.5",
"js-cookie": "^3.0.1",
"less": "^3.0.4",
"less-loader": "^5.0.0",
"lib-flexible": "^0.3.2",
"path": "^0.12.7",
"pinia": "^2.0.32",
"pinia-plugin-persist": "^1.0.0",
"postcss-px2rem": "^0.3.0",
"vant": "^2.12.53",
"vue": "^2.7.0",
"vue-cookies": "^1.8.2",
"vue-router": "^3.2.0",
"vuex": "^3.4.0"
},
"devDependencies": {
"@vue/cli-plugin-babel": "~4.5.19",
"@vue/cli-plugin-router": "~4.5.19",
"@vue/cli-plugin-vuex": "~4.5.19",
"@vue/cli-service": "~4.5.19",
"babel-plugin-import": "^1.13.6",
"prettier": "2.8.4",
"vue-template-compiler": "^2.7.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
以上就是目录
遇到严重问题就是使用$cookies,发现一直报错很无奈!说我的$cookies未定义!!!
后来问了chatgpd
是因为pinia内没有vue实例所以没有this指向!因此报错!
接下来就在模块内写了一个vue实例返回给pinia!
import Vue from 'vue'
import { defineStore } from 'pinia'
import VueCookies from 'vue-cookies'
Vue.use(VueCookies)
const app = new Vue({
data() {
return {
token: ''
}
},
created() {
this.token = this.$cookies.get('loginKK') || ''
}
})
export const useUserStore = defineStore('counter', {
state: () => ({
token: app.token
}),
getters: {},
actions: {
login() {
app.token = 'newToken'
console.log(this.token)
app.$cookies.set('loginKK', app.token)
}
}
})
export default useUserStore
以上都是完整代码了!