javascript - 如何确保 vuex 商店包含在我的构建中?
问题描述
我有一个使用 vue cli 3 的 Vue 应用程序。我正在按照此处的指南尝试构建我的应用程序vue-cli-service build --target wc --name my-element [entry]
为了测试输出,我有一个 index.html 文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<my-project></my-project>
<script src="https://unpkg.com/vue"></script>
<script src="my-project.min.js"></script>
</body>
</html>
它指向 my-project.min.js 的这一部分:
我的 main.js:
import "@babel/polyfill";
import Vue from "vue";
import MyProject from "./MyProject.vue";
import router from "./router";
import store from "./store/index";
Vue.config.productionTip = false;
new Vue({
router,
store,
render: h => h(MyProject),
}).$mount("#app");
我的 store 被划分为 action、getter、mutations 和 state 的单独文件:
store/index.js 看起来像这样:
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
import state from "./state";
import * as getters from "./getters";
import * as mutations from "./mutations";
import * as actions from "./actions";
export default new Vuex.Store({
state,
getters,
mutations,
actions,
});
项目中的所有内容在开发过程中都运行良好,但是当我构建项目时,vuex 似乎没有被正确添加。
解决方案
看起来您只需要在 index.html 中包含一个 Vuex 的 CDN(在 Vue 的 CDN 之后)。
根据这个页面Vuex - 安装#直接下载/光盘
在 Vue 之后包含 Vuex,它会自动安装
Vue CLI 3 - Build Targets文档说 Vue 是外部化的,您已经使用 Vue 的 CDN 处理了这一点,但我想这同样适用于任何其他通过声明连接到 Vue 的库(Vue.use()
对于例如 Vue 路由器,如果你的组件定义了子路由)。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<my-project></my-project>
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>
<script src="my-project.min.js"></script>
</body>
</html>
在 Web 组件中加载 Store
由于在 dev 模式下main.js
会将您的 store 添加到 Vue,因此在 prod 模式下需要将 store 注入到 Web 组件中。以下添加足以为您提供工作this.$store
属性,请参阅Store not working in web components
<template>
...
</template>
<script>
import store from "../store/index";
export default {
props: [...],
store,
...
}
推荐阅读
- angular - 内置指令、属性指令和结构指令有什么区别?
- xamarin.forms - 无法从代码中创建的数据模板获取父绑定上下文
- javascript - 浏览器上的 JavaScript 模块
- android - Gson 不将值分配给直接内部对象,但如果我使用数组,它会分配值
- html - 将文本字段转换为下拉字段
- gluon-mobile - Gluon 示例应用程序在 ios 设备上失败
- python - 在python中赋值之前引用的局部变量'form'
- android - 单击 TextField 时键盘被关闭
- c++ - 按值传递指针和引用之间的区别?
- python-3.x - 系统错误:解析时出现意外的 EOF