#node.js #vue.js #vuex
#node.js #vue.js #vuex
Вопрос:
Я новичок в Vuex, и у меня проблема. Я не могу правильно обслуживать свое приложение npm run serve
. Я могу открыть приложение на localhost, но оно ничего не отображает, только HTML-текст со стилизованным цветом фона. Ранее я делал npm run build
F:JavascriptCodeHighlighter>npm run build
> code-highlighter@0.1.0 build F:JavascriptCodeHighlighter
> vue-cli-service build
- Building for production...
DONE Compiled successfully in 6447ms 08:44:40
File Size Gzipped
distjschunk-vendors.74c072d0.js 120.47 KiB 42.78 KiB
distjsapp.f18138cd.js 5.18 KiB 2.08 KiB
distcssapp.60b393b9.css 1.78 KiB 0.65 KiB
Images and other types of assets omitted.
DONE Build complete. The dist directory is ready to be deployed.
INFO Check out deployment instructions at https://cli.vuejs.org/guide/deployment.html
Тогда я делаю npm run serve
F:JavascriptCodeHighlighter>npm run serve
> code-highlighter@0.1.0 serve F:JavascriptCodeHighlighter
> vue-cli-service serve
INFO Starting development server...
98% after emitting CopyPlugin
DONE Compiled successfully in 4139ms 08:45:52
App running at:
- Local: http://localhost:8080/
- Network: http://192.168.0.116:8080/
Note that the development build is not optimized.
To create a production build, run npm run build
когда я открываю http://localhost:8080/
и открываю консоль. Имеется 1 ошибка и 2 предупреждения.
[Vue warn]: Property "$store" was accessed during render but is not defined on instance.
at <Header>
at <App>
[Vue warn]: Unhandled error during execution of render function
at <Header>
at <App>
Uncaught TypeError: Cannot read property 'getters' of undefined
Есть мой каталог
И вот мой полный код
main.js
import { createApp } from 'vue'
import { createStore } from 'vuex'
import { store } from './store/store'
import App from './App.vue'
// console.log(store);
const app = createApp(App).mount('#app');
const vuestore = createStore(store);
app.use(vuestore);
store.js
import Vuex from 'vuex';
export const store = new Vuex.Store({
strict:true,
state:{
title: 'Code Highlighter',
copyright:{
license : 'MIT',
author : 'Philip Purwoko',
repository : 'https://github.com/PhilipPurwoko/CodeHighlighter'
},
api: "https://highlight-code-api.jefrydco.vercel.app/api",
langs: ["javascript", "python"]
},
getters:{
getTitle:state=>{
return state.title;
},
getCopyright:state=>{
return state.copyright;
},
getAPI:state=>{
return state.api;
},
getLangs:state=>{
return state.langs;
}
}
});
App.vue
<template>
<main>
<app-header></app-header>
<code-block></code-block>
<app-footer></app-footer>
</main>
</template>
<script>
import Header from "./components/Header.vue";
import Footer from "./components/Footer.vue";
import CodeBlock from "./components/CodeBlock.vue";
export default {
components: {
"app-header": Header,
"code-block": CodeBlock,
"app-footer": Footer,
},
};
</script>
CodeBlock.vue
<template>
<div>
<form>
<strong class="monospace">Select Language</strong>
<select v-model="lang" @change="highlight">
<option selected disabled>Choose Language</option>
<option v-bind:key="lan" v-for="lan in getLangs">{{ lan }}</option>
</select>
</form>
<section class="code-container">
<textarea class="code-block" v-model="code" @input="highlight" ></textarea>
<div class="code-block formated" v-html="formated"></div>
</section>
</div>
</template>
<script>
import axios from "axios";
import { mapGetters } from 'vuex';
export default {
data: function() {
return {
lang: "",
code: "",
formated: ""
};
},
computed:{
...mapGetters([
'getAPI',
'getLangs',
'getFormated',
'getCode'
])
},
methods: {
highlight() {
if (this.code == "") {
this.code = " ";
}
if (this.lang != "") {
axios
.post(
this.getAPI `?lang=${this.lang}`,
{
code: this.code
}
)
.then(res => {
this.formated = res.data.data;
});
} else {
this.formated = "<p class='monospace' style='color:azure;'>No language selected. Please select a language</p>";
}
}
}
};
</script>
package.json
{
"name": "code-highlighter",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"axios": "^0.20.0",
"core-js": "^3.6.5",
"vue": "^3.0.0",
"vuex": "^4.0.0-beta.4"
},
"devDependencies": {
"@vue/cli-plugin-babel": "~4.5.0",
"@vue/cli-plugin-eslint": "~4.5.0",
"@vue/cli-service": "~4.5.0",
"@vue/compiler-sfc": "^3.0.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^7.0.0-0"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/vue3-essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
Вы также можете получить доступ к моему репозиторию github здесь (https://github.com/PhilipPurwoko/CodeHighlighter/tree/restart ). Я действительно ценю все ваши ответы. Спасибо
Ответ №1:
Сначала, пожалуйста, прочитайте документацию Vuex для Vue 3. Я обнаружил допущенную вами ошибку в том, что вы должны использовать плагин Vue перед монтированием экземпляра Vue. Это должно выглядеть так. Удачи!
import { createApp } from 'vue'
import { store } from './store'
import App from './App.vue'
// Create vue instance
const app = createApp(App);
// Install the plugin first
app.use(store);
// Mount your app
app.mount('#app');
Комментарии:
1. Отлично. Эта проблема решена. Спасибо. Но, на самом деле, мы должны
import { store } from './store/store'
, потому что мы хотим импортироватьstore
переменную внутри папкиstore.js
store