主讲vuex的配置和使用,其他配置不细讲
上手项目的目录结构
安装依赖
cnpm i vuex -S
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
module.exports = {
entry: {
app: './src/main.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
devServer: {
port: 3000,
contentBase: './dist',
progress: true
},
mode: 'development',
plugins: [
new HtmlWebpackPlugin({
title: 'webpack-vuex', // 生成的HTML文件的标题
template: './src/index.html' // 使用的模板路径
}),
new VueLoaderPlugin()
],
module: {
rules: [{
test: /\.vue$/,
use: [
'vue-loader'
]
}]
}
}
package.json
{
"name": "webpack4-vuex",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --config webpack.config.js",
"start": "webpack-dev-server --open"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"html-webpack-plugin": "^3.2.0",
"vue-loader": "^15.7.1",
"vue-template-compiler": "^2.6.10",
"webpack": "^4.39.2",
"webpack-cli": "^3.3.7"
},
"dependencies": {
"vue": "^2.6.10",
"vuex": "^3.1.1"
}
}
main.js
import Vue from 'vue'
import App from './App.vue'
import Vuex from 'vuex'
Vue.use(Vuex)
var store=new Vuex.Store({
// 如果组件想要访问state中的数据,只能通过this.$store.state.***来访问
state:{
count:0
},
// 组件如果想要调用mutations,只能通过this.$store.commit("方法名")来调用
mutations:{
increment(state){
state.count++
},
// mutations的函数的参数列表中最多只能有两个参数,第一个是state,
// 第二个是commit传递过来
remove(state,num){
state.count-=num
}
},
// 如果store中的state中的数据在对外提供的时候需要做一层包装,推荐使用getters,
// 组件通过this.$store.getters.***来调用getters中的函数
getters:{
open(state){
return '当前的数量是'+state.count
}
}
})
var vm=new Vue({
el:'#app',
data:{
},
render:function(createElements){
return createElements(App)
},
store
})
amount.vue
<template>
<div>
<h2>总数:{{$store.state.count}}</h2>
<h3>{{$store.getters.open}}</h3>
</div>
</template>
<script>
</script>
<style>
</style>
counter.vue
<template>
<div>
<input type="button" value="增加" @click="add">
<input type="button" value="减少" @click="reduce">
<br>
<input type="text" v-model="$store.state.count">
</div>
</template>
<script>
export default{
data(){
return {
}
},
methods:{
add(){
// 不要这么用,不符合vuex的设计理念
// this.$store.state.count++
this.$store.commit("increment")
},
reduce(){
this.$store.commit("remove",3)
}
}
}
</script>
<style>
</style>
App.vue
<template>
<div>
<h1>这是App组件</h1>
<counter></counter>
<amount></amount>
</div>
</template>
<script>
import counter from './components/counter.vue'
import amount from './components/amount.vue'
export default{
data(){
return {
};
},
components:{
counter,
amount
}
}
</script>
<style>
</style>
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="app">
</div>
</body>
</html>
终端运行命令
cnpm run start
运行结果