src/store/index.js(默认代码)
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
mutations: {},
actions: {}
})
views/myvuex.vue:在路由中访问state上的count
<template>
<div>
我是vuex页面
<h1>{{this.$store.state.count}}h1>
div>
template>
main.js
import Vue from "vue"
import router from "./router"
import vueRouter from "vue-router"
import App from "./App.vue"
Vue.use(vueRouter);
Vue.config.productionTip = false;
new Vue({
el: "#app",
router,
render: h => h(App)
})
App.vue:使用路由
<template>
<div>
<router-link to="/myvuex"">我的vuexrouter-link>
<h1>内容展示区域:h1>
<router-view>router-view>
div>
template>
router/index.js:引入和配置路由路径
import vueRouter from "vue-router"
// 引入路由
import myvuex from "@/views/myvuex"
// 配置路由
// 创建路由对象router
const router = new vueRouter({
routes: [
{
path: "/myvuex",
component: myvuex
},
],
});
// 导出路由
export default router;
报错:
roperty or method “$store” is not defined on the instance but referenced during render.
解决在main.js中引入store
import Vue from "vue"
import router from "./router"
import vueRouter from "vue-router"
import App from "./App.vue"
import store from './store'
Vue.use(vueRouter);
Vue.config.productionTip = false;
new Vue({
el: "#app",
router,
store,
render: h => h(App)
})
报错:
This dependency was not found:
* store in ./src/main.js
To install it, you can run: npm install --save store
被上面这个报错误导,输入了上述安装命令,但是真正的错误原因是:
store的引入路径不正确,因为真正要引入的是store文件夹下的index.js文件
修改后的main.js
import Vue from "vue"
import router from "./router"
import vueRouter from "vue-router"
import App from "./App.vue"
// 引入store下的index.js
import store from './store/index'
Vue.use(vueRouter);
Vue.config.productionTip = false;
new Vue({
el: "#app",
router,
store,
render: h => h(App)
})
vue2却配置了vuex4
此时要看看package.json文件中的依赖
"dependencies": {
"axios": "^1.1.3",
"core-js": "^3.6.5",
"save": "^2.9.0",
"store": "^2.0.12",
"vue": "^2.6.11",
"vue-router": "^3.2.0",
"vuex": "^3.6.2"
},
该降级的降级