脚本宝典收集整理的这篇文章主要介绍了

Vuex? 和 TypeScript 的 Webpack4.+ 尝鲜

脚本宝典小编觉得挺不错的,现在分享给大家,也给大家做个参考,希望能帮助你少写一行代码,多一份安全和惬意。
<p><code></p> <p><span class="img-wrap"><img data-src="/img/bVbbhsr?w=800&amp;h=800" src="/img/bVbbhsr?w=800&amp;h=800" alt="图片描述" title="图片描述" style="cursor: pointer; display: inline;"></span></p> <blockquote><p>静态类型系统能帮助你有效防止许多潜在的运行时错误,而且随着你的应用日渐丰满会更加显著。这就是为什么 <a href="http://www.js-code.com/tag/vue" title="Vue" target="_blank">Vue</a> 不仅仅为 <a href="http://www.js-code.com/tag/vue" title="Vue" target="_blank">Vue</a> core 提供了针对 TypeScript 的官方类型声明,还为 <a href="http://www.js-code.com/tag/vue" title="浏览关于“Vue”的文章" target="_blank" class="tag_link">Vue</a> Router 和 Vuex 也提供了相应的声明文件</p></blockquote> <h2 id="articleHeader0">TsConfig配置</h2> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="{ &quot;compilerOptions&quot;: { // ts 文件编译成 js 文件的时候,同时生成对应的 map 文件 &quot;sourceMap&quot;: true, &quot;strict&quot;: true, &quot;strictNullChecks&quot;: true, // 当表达式和申明 类型为any时,是否需要发出警告,设置true,则不警告 &quot;noImplicitAny&quot;: true, // 设置为true时,如果不是函数中的所有路径都有返回值,则提示Error &quot;noImplicitReturns&quot;: true, // module 用于指定模块的代码生成规则,可以使用 commonjs 、 amd 、 umd 、 system 、 es6 、 es2015 、 none 这些选项。 // 选择commonJS,会生成符合commonjs规范的文件,使用amd,会生成满足amd规范的文件,使用system会生成使用ES6的 // system.import的代码。使用es6或者是es2015会生产包含ES6特性的代码。 &quot;module&quot;: &quot;es2015&quot;, &quot;moduleResolution&quot;: &quot;node&quot;, // 设置为true时,则允许从没有默认导出的模块中默认导入(也就是不做检查) &quot;allowSyntheticDefaultImports&quot;: true, // 设置为true,则支持ES7的装饰器特性 &quot;experimentalDecorators&quot;: true, // target 用于指定生成代码的兼容版本,可以从es3,es5,es2015,es6中选择一个,如果不设置,默认生产的代码兼容到es3 &quot;target&quot;: &quot;es5&quot; }, &quot;include&quot;: [ &quot;./src/**/*&quot; ] }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="javascript hljs"><code class="js">{ <span class="hljs-string">"compilerOptions"</span>: { <span class="hljs-comment">// ts 文件编译成 js 文件的时候,同时生成对应的 map 文件</span> <span class="hljs-string">"source<a href="http://www.js-code.com/tag/map" title="浏览关于“Map”的文章" target="_blank" class="tag_link">Map</a>"</span>: <span class="hljs-literal"><a href="http://www.js-code.com/tag/true" title="浏览关于“true”的文章" target="_blank" class="tag_link">true</a></span>, <span class="hljs-string">"strict"</span>: <span class="hljs-literal">true</span>, <span class="hljs-string">"strictNullChecks"</span>: <span class="hljs-literal">true</span>, <span class="hljs-comment">// 当表达式和申明 类型为any时,是否需要发出警告,设置true,则不警告</span> <span class="hljs-string">"noImplicitAny"</span>: <span class="hljs-literal">true</span>, <span class="hljs-comment">// 设置为true时,如果不是函数中的所有路径都有返回值,则提示Error</span> <span class="hljs-string">"noImplicitReturns"</span>: <span class="hljs-literal">true</span>, <span class="hljs-comment">// module 用于指定模块的代码生成规则,可以使用 commonjs 、 amd 、 umd 、 system 、 <a href="http://www.js-code.com/tag/es6" title="浏览关于“es6”的文章" target="_blank" class="tag_link">es6</a> 、 es2015 、 none 这些选项。</span> <span class="hljs-comment">// 选择commonJS,会生成符合commonjs规范的文件,使用amd,会生成满足amd规范的文件,使用system会生成使用ES6的</span> <span class="hljs-comment">// system.import的代码。使用es6或者是es2015会生产包含ES6特性的代码。</span> <span class="hljs-string">"module"</span>: <span class="hljs-string">"es2015"</span>, <span class="hljs-string">"moduleResolution"</span>: <span class="hljs-string">"<a href="http://www.js-code.com/tag/node" title="浏览关于“node”的文章" target="_blank" class="tag_link">node</a>"</span>, <span class="hljs-comment">// 设置为true时,则允许从没有默认导出的模块中默认导入(也就是不做检查)</span> <span class="hljs-string">"<a href="http://www.js-code.com/tag/all" title="浏览关于“all”的文章" target="_blank" class="tag_link">all</a>owSyntheticDefault<a href="http://www.js-code.com/tag/import" title="浏览关于“Import”的文章" target="_blank" class="tag_link">Import</a>s"</span>: <span class="hljs-literal">true</span>, <span class="hljs-comment">// 设置为true,则支持ES7的装饰器特性</span> <span class="hljs-string">"experimentalDecorators"</span>: <span class="hljs-literal">true</span>, <span class="hljs-comment">// target 用于指定生成代码的兼容版本,可以从es3,<a href="http://www.js-code.com/tag/es5" title="浏览关于“es5”的文章" target="_blank" class="tag_link">es5</a>,es2015,es6中选择一个,如果不设置,默认生产的代码兼容到es3</span> <span class="hljs-string">"target"</span>: <span class="hljs-string">"es5"</span> }, <span class="hljs-string">"<a href="http://www.js-code.com/tag/in" title="浏览关于“in”的文章" target="_blank" class="tag_link">in</a>clude"</span>: [ <span class="hljs-string">"./src/**/*"</span> ] }</code></pre> <p>配置参考:</p> <ul> <li><a href="https://www.typescriptlang.org/docs/handbook/tsconfig-json.html" rel="nofollow noreferrer" target="_blank">官方文档tsconfig解析</a></li> <li><a href="http://json.schemastore.org/tsconfig" rel="nofollow noreferrer" target="_blank">tsconfig的JSON文档</a></li> </ul> <h2 id="articleHeader1">Webpack的基础配置一览</h2> <p>每个项目最重要的一部分个人感觉是webpack的配置,只有配置好webpack部分后续才能顺利进行开发</p> <p>这里webpack使用了4.+的版本,所以算是体验了较为新的webpack,其中和旧版的有些区别,这里不做介绍</p> <p>先贴出webpack的配置代码</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="const path = require('path') const webpack = require('webpack') const VueLoaderPlugin = require('vue-loader/lib/plugin') module.exports = { mode: process.env.NODE_ENV === 'production' ? 'production' : 'development', entry: './src/index.ts', output: { path: path.resolve(__dirname, './dist'), publicPath: '/dist/', filename: 'build.js' }, module: { rules: [ { test: /.vue$/, loader: 'vue-loader', options: { loaders: { 'scss': 'vue-style-loader!css-loader!sass-loader', 'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax', } } }, { test: /.tsx?$/, loader: 'ts-loader', exclude: /node_modules/, options: { transpileOnly: true, appendTsSuffixTo: [/.vue$/] } } ] }, resolve: { extensions: ['.ts', '.js', '.vue', '.josn'], alias: { 'vue$': 'vue/dist/vue.esm.js' } }, devServer: { contentBase: './public', host: 'localhost', port: '8080', open: true, hot: true, inline: true, historyApiFallback: true, noInfo: true }, performance: { hints: false }, devtool: '#eval-source-map', plugins: [ new VueLoaderPlugin() ] } if (process.env.NODE_ENV === 'production') { module.exports.devtool = '#source-map' module.exports.plugins = (module.exports.plugins || []).concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '&quot;production&quot;' } }), new webpack.optimize.UglifyJsPlugin({ sourceMap: true, compress: { warnings: false } }), new webpack.LoaderOptionsPlugin({ minimize: true }) ]) } else { module.exports.plugins = (module.exports.plugins || []).concat([ new webpack.HotModuleReplacementPlugin() ]) } " title="" data-original-title="复制"></span> </div> </p></div> <pre class="javascript hljs"><code class="js"><span class="hljs-keyword"><a href="http://www.js-code.com/tag/const" title="浏览关于“const”的文章" target="_blank" class="tag_link">const</a></span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>) <span class="hljs-keyword">const</span> webpack = <span class="hljs-built_in">require</span>(<span class="hljs-string">'webpack'</span>) <span class="hljs-keyword">const</span> VueLoaderPlugin = <span class="hljs-built_in">require</span>(<span class="hljs-string">'vue-loader/lib/<a href="http://www.js-code.com/tag/plugin" title="浏览关于“plugin”的文章" target="_blank" class="tag_link">plugin</a>'</span>) <span class="hljs-built_in">module</span>.<a href="http://www.js-code.com/tag/export" title="浏览关于“export”的文章" target="_blank" class="tag_link">export</a>s = { <span class="hljs-attr">mode</span>: process.env.NODE_ENV === <span class="hljs-string">'production'</span> ? <span class="hljs-string">'production'</span> : <span class="hljs-string">'development'</span>, <span class="hljs-attr">en<a href="http://www.js-code.com/tag/try" title="浏览关于“try”的文章" target="_blank" class="tag_link">try</a></span>: <span class="hljs-string">'./src/index.ts'</span>, <span class="hljs-attr">output</span>: { <span class="hljs-attr">path</span>: path.resolve(__dir<a href="http://www.js-code.com/tag/name" title="浏览关于“name”的文章" target="_blank" class="tag_link">name</a>, <span class="hljs-string">'./dist'</span>), <span class="hljs-attr"><a href="http://www.js-code.com/tag/public" title="浏览关于“public”的文章" target="_blank" class="tag_link">public</a>Path</span>: <span class="hljs-string">'/dist/'</span>, <span class="hljs-attr">filename</span>: <span class="hljs-string">'build.js'</span> }, <span class="hljs-attr">module</span>: { <span class="hljs-attr">rules</span>: [ { <span class="hljs-attr">test</span>: <span class="hljs-regexp">/.vue$/</span>, <span class="hljs-attr">loader</span>: <span class="hljs-string">'vue-loader'</span>, <span class="hljs-attr"><a href="http://www.js-code.com/tag/option" title="浏览关于“option”的文章" target="_blank" class="tag_link">option</a>s</span>: { <span class="hljs-attr">loaders</span>: { <span class="hljs-string">'scss'</span>: <span class="hljs-string">'vue-style-loader!css-loader!sass-loader'</span>, <span class="hljs-string">'sass'</span>: <span class="hljs-string">'vue-style-loader!css-loader!sass-loader?indentedSyntax'</span>, } } }, { <span class="hljs-attr">test</span>: <span class="hljs-regexp">/.tsx?$/</span>, <span class="hljs-attr">loader</span>: <span class="hljs-string">'ts-loader'</span>, <span class="hljs-attr">exclude</span>: <span class="hljs-regexp">/node_modules/</span>, <span class="hljs-attr">options</span>: { <span class="hljs-attr">transpileOnly</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">appendTsSuffixTo</span>: [<span class="hljs-regexp">/.vue$/</span>] } } ] }, <span class="hljs-attr">resolve</span>: { <span class="hljs-attr">extensions</span>: [<span class="hljs-string">'.ts'</span>, <span class="hljs-string">'.js'</span>, <span class="hljs-string">'.vue'</span>, <span class="hljs-string">'.josn'</span>], <span class="hljs-attr">alias</span>: { <span class="hljs-string">'vue$'</span>: <span class="hljs-string">'vue/dist/vue.esm.js'</span> } }, <span class="hljs-attr">devServer</span>: { <span class="hljs-attr">contentBase</span>: <span class="hljs-string">'./public'</span>, <span class="hljs-attr">host</span>: <span class="hljs-string">'localhost'</span>, <span class="hljs-attr">port</span>: <span class="hljs-string">'8080'</span>, <span class="hljs-attr"><a href="http://www.js-code.com/tag/open" title="浏览关于“open”的文章" target="_blank" class="tag_link">open</a></span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">hot</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">inline</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr"><a href="http://www.js-code.com/tag/history" title="浏览关于“history”的文章" target="_blank" class="tag_link">history</a>ApiFallback</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">noInfo</span>: <span class="hljs-literal">true</span> }, <span class="hljs-attr">per<a href="http://www.js-code.com/tag/form" title="浏览关于“form”的文章" target="_blank" class="tag_link">form</a>ance</span>: { <span class="hljs-attr">h<a href="http://www.js-code.com/tag/int" title="浏览关于“int”的文章" target="_blank" class="tag_link">int</a>s</span>: <span class="hljs-literal"><a href="http://www.js-code.com/tag/false" title="浏览关于“false”的文章" target="_blank" class="tag_link">false</a></span> }, <span class="hljs-attr">devtool</span>: <span class="hljs-string">'#<a href="http://www.js-code.com/tag/eval" title="浏览关于“eval”的文章" target="_blank" class="tag_link">eval</a>-source-map'</span>, <span class="hljs-attr">plugins</span>: [ <span class="hljs-keyword"><a href="http://www.js-code.com/tag/new" title="浏览关于“new”的文章" target="_blank" class="tag_link">new</a></span> VueLoaderPlugin() ] } <span class="hljs-keyword"><a href="http://www.js-code.com/tag/if" title="浏览关于“if”的文章" target="_blank" class="tag_link">if</a></span> (process.env.NODE_ENV === <span class="hljs-string">'production'</span>) { <span class="hljs-built_in">module</span>.exports.devtool = <span class="hljs-string">'#source-map'</span> <span class="hljs-built_in">module</span>.exports.plugins = (<span class="hljs-built_in">module</span>.exports.plugins || []).concat([ <span class="hljs-keyword">new</span> webpack.DefinePlugin({ <span class="hljs-string">'process.env'</span>: { <span class="hljs-attr">NODE_ENV</span>: <span class="hljs-string">'"production"'</span> } }), <span class="hljs-keyword">new</span> webpack.optimize.UglifyJsPlugin({ <span class="hljs-attr">sourceMap</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">compress</span>: { <span class="hljs-attr">warnings</span>: <span class="hljs-literal">false</span> } }), <span class="hljs-keyword">new</span> webpack.LoaderOptionsPlugin({ <span class="hljs-attr">minimize</span>: <span class="hljs-literal">true</span> }) ]) } <span class="hljs-keyword"><a href="http://www.js-code.com/tag/else" title="浏览关于“else”的文章" target="_blank" class="tag_link">else</a></span> { <span class="hljs-built_in">module</span>.exports.plugins = (<span class="hljs-built_in">module</span>.exports.plugins || []).concat([ <span class="hljs-keyword">new</span> webpack.HotModuleReplacementPlugin() ]) } </code></pre> <p>注意点:</p> <ul> <li>vue-loader v15需要在webpack插件中添加VueLoaderPlug<a href="http://www.js-code.com/tag/in" title="in" target="_blank">in</a>插件</li> <li>webpack4.+需要指定mode,开发模式还是生产模式</li> <li>注意ts-loader的配置</li> </ul> <p>这里只是简单进行webpack配置,没有太完整地根据完整的项目来进行配置,只是简单配置了生产环境下的代码混淆压缩,以及对应的开发服务器和热更新等,有需要其他功能扩展的自行配置。</p> <h2 id="articleHeader2">Vue环境搭建配置</h2> <h3 id="articleHeader3">vue-shims.d.ts的添加</h3> <p>这个是比较重要的一个配置,该文件需要放到vue的入口文件中,具体的d.ts代码如下:</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="declare module '*.vue' { import Vue from 'vue' export default Vue }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="typescript hljs"><code class="ts"><span class="hljs-keyword">declare</span> <span class="hljs-keyword">module</span> '*.vue' { <span class="hljs-keyword">import</span> Vue <span class="hljs-keyword">from</span> <span class="hljs-string">'vue'</span> <span class="hljs-keyword">export</span> <span class="hljs-keyword"><a href="http://www.js-code.com/tag/default" title="浏览关于“default”的文章" target="_blank" class="tag_link">default</a></span> Vue }</code></pre> <p>目的是让ts能够识别到vue的静态类型</p> <h3 id="articleHeader4">vue的入口文件</h3> <p><a href="http://www.js-code.com/tag/in" title="in" target="_blank">in</a>dex.ts:</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="import Vue from 'vue' import App from './App.vue' // vuex部分 import store from './store' new Vue({ el: '#app', store, render: h => h(App),<br /> })<br /> " title="" data-original-title="复制"></span> </div> </p></div> <pre class="typescript hljs"><code class="ts"><span class="hljs-keyword">import</span> Vue <span class="hljs-keyword">from</span> <span class="hljs-string">'vue'</span> <span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./App.vue'</span> <span class="hljs-comment">// vuex部分</span> <span class="hljs-keyword">import</span> store <span class="hljs-keyword">from</span> <span class="hljs-string">'./store'</span> <span class="hljs-keyword">new</span> Vue({ el: <span class="hljs-string">'#app'</span>, store, render: <span class="hljs-function"><span class="hljs-params">h</span> =&gt;</span> h(App), }) </code></pre> <p>入口文件跟普通的js写法没有太多的区别,只是文件类型为ts。</p> <h2 id="articleHeader5">开始写vue的单文件页面和组件</h2> <h3 id="articleHeader6">单文件页面模板</h3> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="<a href="http://www.js-code.com/tag/button" title="button" target="_blank">button</a>" <a href="http://www.js-code.com/tag/class" title="class" target="_blank">class</a>="copyCode code-tool" data-toggle="tooltip" data-placement="<a href="http://www.js-code.com/tag/top" title="top" target="_blank">top</a>" data-clipboard-<a href="http://www.js-code.com/tag/text" title="text" target="_blank">text</a>="<template><br /> ...<br /> </template></p> <p><script lang=&quot;ts&quot;> ... </script></p> <style> ... </style> <p>" title="" data-original-title="复制"></span> </div> </p></div> <pre class="javascript hljs"><code class="js">&lt;template&gt; ... &lt;<span class="hljs-regexp">/template&gt; &lt;script lang="ts"&gt; ... &lt;/</span>script&gt; <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="undefined"> ... </span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span></span></code></pre> <p>主要是在script项中把lang写为ts类型</p> <h3 id="articleHeader7">使用装饰器来实现组件和页面</h3> <p>这里我们主要使用两个装饰器库vue-property-decorator 和 vuex-<a href="http://www.js-code.com/tag/class" title="class" target="_blank">class</a>, vue-property-decorator其是基于vue-class-得component的基础扩展修改的。</p> <ol> <li>大致了解一下vue-property-decorator的装饰器的用法</li> </ol> <p>一共有七个装饰器:</p> <ul> <li><code>@Emit</code></li> <li><code>@Inject</code></li> <li><code>@Model</code></li> <li><code>@<a href="http://www.js-code.com/tag/prop" title="Prop" target="_blank">Prop</a></code></li> <li><code>@Provide</code></li> <li><code>@Watch</code></li> <li> <code>@Component</code> (<strong><a href="http://www.js-code.com/tag/export" title="export" target="_blank">export</a>ed from</strong> <code>vue-class-component</code>)</li> </ul> <p>这里使用vue-property-decorator的例子来做解析</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="import { Component, Emit, Inject, Model, Prop, Provide, Vue, Watch } from 'vue-property-decorator' const s = Symbol('baz') @Component export class MyComponent extends Vue { @Emit() addToCount(n: number){ this.count += n } @Emit('reset') resetCount(){ this.count = 0 } @Inject() foo: string @Inject('bar') bar: string @Inject({from: 'optional', default: 'default'}) optional: string @Inject(s) baz: string @Model('change') checked: boolean @Prop() propA: number @Prop({ default: 'default value' }) propB: string @Prop([String, Boolean]) propC: string | boolean @Provide() foo = 'foo' @Provide('bar') baz = 'bar' @Watch('child') onChildChanged(val: string, oldVal: string) { } @Watch('person', { immediate: true, deep: true }) onPersonChanged(val: Person, oldVal: Person) { } } " title="" data-original-title="复制"></span> </div> </p></div> <pre class="typescript hljs"><code class="ts"><span class="hljs-keyword">import</span> { Component, Emit, Inject, Model, <a href="http://www.js-code.com/tag/prop" title="浏览关于“Prop”的文章" target="_blank" class="tag_link">Prop</a>, Provide, Vue, Watch } <span class="hljs-keyword">from</span> <span class="hljs-string">'vue-property-decorator'</span> <span class="hljs-keyword">const</span> s = Symbol(<span class="hljs-string">'baz'</span>) <span class="hljs-meta">@Component</span> <span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> MyComponent <span class="hljs-keyword"><a href="http://www.js-code.com/tag/extends" title="浏览关于“extends”的文章" target="_blank" class="tag_link">extends</a></span> Vue { <span class="hljs-meta">@Emit</span>() addToCount(n: <span class="hljs-built_in">number</span>){ <span class="hljs-keyword"><a href="http://www.js-code.com/tag/this" title="浏览关于“this”的文章" target="_blank" class="tag_link">this</a></span>.count += n } <span class="hljs-meta">@Emit</span>(<span class="hljs-string">'<a href="http://www.js-code.com/tag/reset" title="浏览关于“reset”的文章" target="_blank" class="tag_link">reset</a>'</span>) resetCount(){ <span class="hljs-keyword">this</span>.count = <span class="hljs-number">0</span> } <span class="hljs-meta">@Inject</span>() foo: <span class="hljs-built_in">string</span> <span class="hljs-meta">@Inject</span>(<span class="hljs-string">'bar'</span>) bar: <span class="hljs-built_in">string</span> <span class="hljs-meta">@Inject</span>({<span class="hljs-keyword">from</span>: <span class="hljs-string">'optional'</span>, <span class="hljs-keyword">default</span>: <span class="hljs-string">'default'</span>}) optional: <span class="hljs-built_in">string</span> <span class="hljs-meta">@Inject</span>(s) baz: <span class="hljs-built_in">string</span> <span class="hljs-meta">@Model</span>(<span class="hljs-string">'change'</span>) checked: <span class="hljs-built_in"><a href="http://www.js-code.com/tag/boolean" title="浏览关于“boolean”的文章" target="_blank" class="tag_link">boolean</a></span> <span class="hljs-meta">@Prop</span>() propA: <span class="hljs-built_in">number</span> <span class="hljs-meta">@Prop</span>({ <span class="hljs-keyword">default</span>: <span class="hljs-string">'default value'</span> }) propB: <span class="hljs-built_in">string</span> <span class="hljs-meta">@Prop</span>([<span class="hljs-built_in"><a href="http://www.js-code.com/tag/String" title="浏览关于“String”的文章" target="_blank" class="tag_link">String</a></span>, <span class="hljs-built_in">Boolean</span>]) propC: <span class="hljs-built_in">string</span> | <span class="hljs-built_in">boolean</span> <span class="hljs-meta">@Provide</span>() foo = <span class="hljs-string">'foo'</span> <span class="hljs-meta">@Provide</span>(<span class="hljs-string">'bar'</span>) baz = <span class="hljs-string">'bar'</span> <span class="hljs-meta">@Watch</span>(<span class="hljs-string">'child'</span>) onChildChanged(val: <span class="hljs-built_in">string</span>, oldVal: <span class="hljs-built_in">string</span>) { } <span class="hljs-meta">@Watch</span>(<span class="hljs-string">'person'</span>, { immediate: <span class="hljs-literal">true</span>, deep: <span class="hljs-literal">true</span> }) onPersonChanged(val: Person, oldVal: Person) { } } </code></pre> <p>相当于js的写法:</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="const s = Symbol('baz') export const MyComponent = Vue.extend({ name: 'MyComponent', inject: { foo: 'foo', bar: 'bar', 'optional': { from: 'optional', default: 'default' }, [s]: s }, model: { prop: 'checked', event: 'change' }, props: { &nbsp; &nbsp;checked: Boolean, &nbsp; &nbsp;propA: Number, propB: { type: String, default: 'default value' }, propC: [String, Boolean], }, data () { return { foo: 'foo', baz: 'bar' } }, provide () { return { foo: this.foo, bar: this.baz } }, methods: { addToCount(n){ this.count += n this.$emit(&quot;add-to-count&quot;, n) }, resetCount(){ this.count = 0 this.$emit(&quot;reset&quot;) }, onChildChanged(val, oldVal) { }, onPersonChanged(val, oldVal) { } }, watch: { 'child': { handler: 'onChildChanged', immediate: false, deep: false }, 'person': { handler: 'onPersonChanged', immediate: true, deep: true } } })" title="" data-original-title="复制"></span> </div> </p></div> <pre class="javascript hljs"><code class="js"><span class="hljs-keyword">const</span> s = <span class="hljs-built_in">Symbol</span>(<span class="hljs-string">'baz'</span>) <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> MyComponent = Vue.extend({ <span class="hljs-attr">name</span>: <span class="hljs-string">'MyComponent'</span>, <span class="hljs-attr">inject</span>: { <span class="hljs-attr">foo</span>: <span class="hljs-string">'foo'</span>, <span class="hljs-attr">bar</span>: <span class="hljs-string">'bar'</span>, <span class="hljs-string">'optional'</span>: { <span class="hljs-attr">from</span>: <span class="hljs-string">'optional'</span>, <span class="hljs-attr">default</span>: <span class="hljs-string">'default'</span> }, [s]: s }, <span class="hljs-attr">model</span>: { <span class="hljs-attr">prop</span>: <span class="hljs-string">'checked'</span>, <span class="hljs-attr"><a href="http://www.js-code.com/tag/event" title="浏览关于“event”的文章" target="_blank" class="tag_link">event</a></span>: <span class="hljs-string">'change'</span> }, <span class="hljs-attr">props</span>: { &nbsp; &nbsp;<span class="hljs-attr">checked</span>: <span class="hljs-built_in">Boolean</span>, &nbsp; &nbsp;<span class="hljs-attr">propA</span>: <span class="hljs-built_in"><a href="http://www.js-code.com/tag/Number" title="浏览关于“Number”的文章" target="_blank" class="tag_link">Number</a></span>, <span class="hljs-attr">propB</span>: { <span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>, <span class="hljs-attr">default</span>: <span class="hljs-string">'default value'</span> }, <span class="hljs-attr">propC</span>: [<span class="hljs-built_in">String</span>, <span class="hljs-built_in">Boolean</span>], }, data () { <span class="hljs-keyword"><a href="http://www.js-code.com/tag/return" title="浏览关于“return”的文章" target="_blank" class="tag_link">return</a></span> { <span class="hljs-attr">foo</span>: <span class="hljs-string">'foo'</span>, <span class="hljs-attr">baz</span>: <span class="hljs-string">'bar'</span> } }, provide () { <span class="hljs-keyword">return</span> { <span class="hljs-attr">foo</span>: <span class="hljs-keyword">this</span>.foo, <span class="hljs-attr">bar</span>: <span class="hljs-keyword">this</span>.baz } }, <span class="hljs-attr">methods</span>: { addToCount(n){ <span class="hljs-keyword">this</span>.count += n <span class="hljs-keyword">this</span>.$emit(<span class="hljs-string">"add-to-count"</span>, n) }, resetCount(){ <span class="hljs-keyword">this</span>.count = <span class="hljs-number">0</span> <span class="hljs-keyword">this</span>.$emit(<span class="hljs-string">"reset"</span>) }, onChildChanged(val, oldVal) { }, onPersonChanged(val, oldVal) { } }, <span class="hljs-attr">watch</span>: { <span class="hljs-string">'child'</span>: { <span class="hljs-attr">handler</span>: <span class="hljs-string">'onChildChanged'</span>, <span class="hljs-attr">immediate</span>: <span class="hljs-literal">false</span>, <span class="hljs-attr">deep</span>: <span class="hljs-literal">false</span> }, <span class="hljs-string">'person'</span>: { <span class="hljs-attr">handler</span>: <span class="hljs-string">'onPersonChanged'</span>, <span class="hljs-attr">immediate</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">deep</span>: <span class="hljs-literal">true</span> } } })</code></pre> <p>相信通过以上的例子我们很容易就看出各个装饰器如何去使用,这里就不再做太多的解释。</p> <ol> <li>再看一下vuex-class的使用方法</li> </ol> <p>同样举例官方的使用列子</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="import Vue from 'vue' import Component from 'vue-class-component' import { State, Getter, Action, Mutation, namespace } from 'vuex-class' const someModule = namespace('path/to/module') @Component export class MyComp extends Vue { @State('foo') stateFoo @State(state => state.bar) stateBar<br /> @Getter('foo') getterFoo<br /> @Action('foo') actionFoo<br /> @Mutation('foo') mutationFoo<br /> @someModule.Getter('foo') moduleGetterFoo</p> <p> @State foo<br /> @Getter bar<br /> @Action baz<br /> @Mutation qux</p> <p> created () {<br /> this.stateFoo // -> store.state.foo<br /> this.stateBar // -> store.state.bar<br /> this.getterFoo // -> store.getters.foo<br /> this.actionFoo({ value: true }) // -> store.dispatch('foo', { value: true })<br /> this.mutationFoo({ value: true }) // -> store.commit('foo', { value: true })<br /> this.moduleGetterFoo // -> store.getters['path/to/module/foo']<br /> }<br /> }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="javascript hljs"><code class="js"><span class="hljs-keyword">import</span> Vue <span class="hljs-keyword">from</span> <span class="hljs-string">'vue'</span> <span class="hljs-keyword">import</span> Component <span class="hljs-keyword">from</span> <span class="hljs-string">'vue-class-component'</span> <span class="hljs-keyword">import</span> { <a href="http://www.js-code.com/tag/state" title="浏览关于“State”的文章" target="_blank" class="tag_link">State</a>, Getter, Action, Mutation, namespace } <span class="hljs-keyword">from</span> <span class="hljs-string">'vuex-class'</span> <span class="hljs-keyword">const</span> someModule = namespace(<span class="hljs-string">'path/to/module'</span>) @Component <span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyComp</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Vue</span> </span>{ @State(<span class="hljs-string">'foo'</span>) stateFoo @State(<span class="hljs-function"><span class="hljs-params">state</span> =&gt;</span> state.bar) stateBar @Getter(<span class="hljs-string">'foo'</span>) getterFoo @Action(<span class="hljs-string">'foo'</span>) actionFoo @Mutation(<span class="hljs-string">'foo'</span>) mutationFoo @someModule.Getter(<span class="hljs-string">'foo'</span>) moduleGetterFoo @State foo @Getter bar @Action baz @Mutation qux created () { <span class="hljs-keyword">this</span>.stateFoo <span class="hljs-comment">// -&gt; store.state.foo</span> <span class="hljs-keyword">this</span>.stateBar <span class="hljs-comment">// -&gt; store.state.bar</span> <span class="hljs-keyword">this</span>.getterFoo <span class="hljs-comment">// -&gt; store.getters.foo</span> <span class="hljs-keyword">this</span>.actionFoo({ <span class="hljs-attr">value</span>: <span class="hljs-literal">true</span> }) <span class="hljs-comment">// -&gt; store.dispatch('foo', { value: true })</span> <span class="hljs-keyword">this</span>.mutationFoo({ <span class="hljs-attr">value</span>: <span class="hljs-literal">true</span> }) <span class="hljs-comment">// -&gt; store.commit('foo', { value: true })</span> <span class="hljs-keyword">this</span>.moduleGetterFoo <span class="hljs-comment">// -&gt; store.getters['path/to/module/foo']</span> } }</code></pre> <h2 id="articleHeader8">Vuex的配置</h2> <h3 id="articleHeader9">store的入口</h3> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="<a href="http://www.js-code.com/tag/button" title="button" target="_blank">button</a>" class="copyCode code-tool" data-toggle="tooltip" data-placement="<a href="http://www.js-code.com/tag/top" title="top" target="_blank">top</a>" data-clipboard-<a href="http://www.js-code.com/tag/text" title="text" target="_blank">text</a>="<a href="http://www.js-code.com/tag/import" title="import" target="_blank">import</a> Vue from 'vue'<br /> <a href="http://www.js-code.com/tag/import" title="import" target="_blank">import</a> Vuex, { StoreOptions } from 'vuex'<br /> import { Root<a href="http://www.js-code.com/tag/state" title="State" target="_blank">State</a> } from './modules/types'<br /> import { profile } from './modules/profile'</p> <p>Vue.use(Vuex)</p> <p><a href="http://www.js-code.com/tag/const" title="const" target="_blank">const</a> store: StoreOptions<RootState> = {<br /> state: {<br /> version: 'v1.0.0'<br /> },<br /> modules: {<br /> profile<br /> }<br /> }</p> <p><a href="http://www.js-code.com/tag/export" title="export" target="_blank">export</a> <a href="http://www.js-code.com/tag/default" title="default" target="_blank">default</a> <a href="http://www.js-code.com/tag/new" title="new" target="_blank">new</a> Vuex.Store<RootState>(store);" title="" data-original-title="复制"></span> </div> </p></div> <pre class="typescript hljs"><code class="ts"><span class="hljs-keyword">import</span> Vue <span class="hljs-keyword">from</span> <span class="hljs-string">'vue'</span> <span class="hljs-keyword">import</span> Vuex, { StoreOptions } <span class="hljs-keyword">from</span> <span class="hljs-string">'vuex'</span> <span class="hljs-keyword">import</span> { RootState } <span class="hljs-keyword">from</span> <span class="hljs-string">'./modules/types'</span> <span class="hljs-keyword">import</span> { profile } <span class="hljs-keyword">from</span> <span class="hljs-string">'./modules/profile'</span> Vue.use(Vuex) <span class="hljs-keyword">const</span> store: StoreOptions&lt;RootState&gt; = { state: { version: <span class="hljs-string">'v1.0.0'</span> }, modules: { profile } } <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">new</span> Vuex.Store&lt;RootState&gt;(store);</code></pre> <p>这里Root<a href="http://www.js-code.com/tag/state" title="State" target="_blank">State</a>只是用于留空,目的是为了注入全局的store,区别于modules的状态</p> <h3 id="articleHeader10">vuex的modules的配置</h3> <ol> <li>写一个全局类型声明</li> </ol> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="export interface RootState { version: string; }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="typescript hljs"><code class="ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword"><a href="http://www.js-code.com/tag/interface" title="浏览关于“interface”的文章" target="_blank" class="tag_link">interface</a></span> RootState { version: <span class="hljs-built_in">string</span>; }</code></pre> <p>version字段就是我们刚才在RootState中定义的字段</p> <ol> <li>定义模板profile</li> </ol> <p>profile模块的类型声明:</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="export interface ProfileState { firstName: string lastName: string }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="typescript hljs"><code class="ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">interface</span> ProfileState { firstName: <span class="hljs-built_in">string</span> lastName: <span class="hljs-built_in">string</span> }</code></pre> <p>profile的模块实现:</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="<a href="http://www.js-code.com/tag/button" title="浏览关于“button”的文章" target="_blank" class="tag_link">button</a>" class="copyCode code-tool" data-toggle="tooltip" data-placement="<a href="http://www.js-code.com/tag/top" title="浏览关于“top”的文章" target="_blank" class="tag_link">top</a>" data-clipboard-<a href="http://www.js-code.com/tag/text" title="浏览关于“text”的文章" target="_blank" class="tag_link">text</a>="import { RootState } from '../types'<br /> import { Module } from 'vuex'<br /> import { ProfileState } from './types'<br /> import { GetterTree, ActionTree, MutationTree } from 'vuex'<br /> import ax<a href="http://www.js-code.com/tag/ios" title="ios" target="_blank">ios</a>, { Ax<a href="http://www.js-code.com/tag/ios" title="ios" target="_blank">ios</a><a href="http://www.js-code.com/tag/promis" title="Promis" target="_blank">Promis</a>e } from 'ax<a href="http://www.js-code.com/tag/ios" title="浏览关于“ios”的文章" target="_blank" class="tag_link">ios</a>'</p> <p><a href="http://www.js-code.com/tag/const" title="const" target="_blank">const</a> state: ProfileState = {<br /> firstName: '',<br /> lastName: ''<br /> }</p> <p><a href="http://www.js-code.com/tag/const" title="const" target="_blank">const</a> getters: GetterTree<ProfileState, RootState> = {<br /> firstName(state) : string {<br /> <a href="http://www.js-code.com/tag/return" title="return" target="_blank">return</a> state.firstName<br /> },<br /> lastName(state) : string {<br /> <a href="http://www.js-code.com/tag/return" title="return" target="_blank">return</a> state.lastName<br /> }<br /> }</p> <p><a href="http://www.js-code.com/tag/const" title="const" target="_blank">const</a> actions: ActionTree<ProfileState, RootState> = {<br /> fetchName({ commit }, id: number): Axios<a href="http://www.js-code.com/tag/promise" title="Promise" target="_blank">Promise</a><ProfileState> {<br /> console.log('action:', id)<br /> return axios.request({<br /> url: 'https://www.apiopen.top/satinCommentApi?id=27610708&amp;page=1'<br /> }).then(res => {<br /> commit('setProfile', {<br /> firstName: 'lin',<br /> lastName: 'guangyu'<br /> })<br /> return res<br /> }).catch(err => {<br /> <a href="http://www.js-code.com/tag/return" title="return" target="_blank">return</a> err<br /> })<br /> }<br /> }</p> <p>const mutations: MutationTree<ProfileState> = {<br /> setProfile(state, payload: ProfileState) {<br /> state.firstName = payload.firstName<br /> state.lastName = payload.lastName<br /> }<br /> }</p> <p>const <a href="http://www.js-code.com/tag/name" title="name" target="_blank">name</a>spaced: <a href="http://www.js-code.com/tag/boolean" title="boolean" target="_blank">boolean</a> = <a href="http://www.js-code.com/tag/true" title="true" target="_blank">true</a>;</p> <p><a href="http://www.js-code.com/tag/export" title="export" target="_blank">export</a> const profile: Module<ProfileState, RootState> = {<br /> namespaced,<br /> state,<br /> getters,<br /> actions,<br /> mutations<br /> };" title="" data-original-title="复制"></span> </div> </p></div> <pre class="typescript hljs"><code class="ts"><span class="hljs-keyword">import</span> { RootState } <span class="hljs-keyword">from</span> <span class="hljs-string">'../types'</span> <span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'vuex'</span> <span class="hljs-keyword">import</span> { ProfileState } <span class="hljs-keyword">from</span> <span class="hljs-string">'./types'</span> <span class="hljs-keyword">import</span> { GetterTree, ActionTree, MutationTree } <span class="hljs-keyword">from</span> <span class="hljs-string">'vuex'</span> <span class="hljs-keyword">import</span> axios, { Axios<a href="http://www.js-code.com/tag/promise" title="浏览关于“Promise”的文章" target="_blank" class="tag_link">Promise</a> } <span class="hljs-keyword">from</span> <span class="hljs-string">'axios'</span> <span class="hljs-keyword">const</span> state: ProfileState = { firstName: <span class="hljs-string">''</span>, lastName: <span class="hljs-string">''</span> } <span class="hljs-keyword">const</span> getters: GetterTree&lt;ProfileState, RootState&gt; = { firstName(state) : <span class="hljs-built_in">string</span> { <span class="hljs-keyword">return</span> state.firstName }, lastName(state) : <span class="hljs-built_in">string</span> { <span class="hljs-keyword">return</span> state.lastName } } <span class="hljs-keyword">const</span> actions: ActionTree&lt;ProfileState, RootState&gt; = { fetchName({ commit }, id: <span class="hljs-built_in">number</span>): Axios<a href="http://www.js-code.com/tag/promis" title="浏览关于“Promis”的文章" target="_blank" class="tag_link">Promis</a>e&lt;ProfileState&gt; { <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'action:'</span>, id) <span class="hljs-keyword">return</span> axios.request({ url: <span class="hljs-string">'https://www.apiopen.top/satinCommentApi?id=27610708&amp;page=1'</span> }).then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> { commit(<span class="hljs-string">'setProfile'</span>, { firstName: <span class="hljs-string">'lin'</span>, lastName: <span class="hljs-string">'guangyu'</span> }) <span class="hljs-keyword">return</span> res }).<a href="http://www.js-code.com/tag/catch" title="浏览关于“catch”的文章" target="_blank" class="tag_link">catch</a>(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> { <span class="hljs-keyword">return</span> err }) } } <span class="hljs-keyword">const</span> mutations: MutationTree&lt;ProfileState&gt; = { setProfile(state, payload: ProfileState) { state.firstName = payload.firstName state.lastName = payload.lastName } } <span class="hljs-keyword">const</span> namespaced: <span class="hljs-built_in">boolean</span> = <span class="hljs-literal">true</span>; <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> profile: Module&lt;ProfileState, RootState&gt; = { namespaced, state, getters, actions, mutations };</code></pre> <p>这里我们就完成了Vuex的配置了,就可以结合装饰器对vuex进行调用,而且具有静态类型提示,十分方便。</p> <p>完成了这一系列的配置我们的尝试已经完成,自己写了个简单的demo,有兴趣可以观看<a href="https://github.com/lgybetter/vue-ts-template" rel="nofollow noreferrer" target="_blank">github</a>怎么配置。</p> <p></code></p>

总结

以上是脚本宝典为你收集整理的

Vuex? 和 TypeScript 的 Webpack4.+ 尝鲜

全部内容,希望文章能够帮你解决

Vuex? 和 TypeScript 的 Webpack4.+ 尝鲜

所遇到的程序开发问题,欢迎加入QQ群277859234一起讨论学习。如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典网站推荐给程序员好友。 本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。

80%的人都看过