文章目录
VueCli 自定义创建项目
1.安装脚手架 npm i @vue/cli -g
2.创建项目 vue create 项目名字
3.自定义创建选项
ESlint代码规范
规范网址 https://standardjs.com/rules-zhcn.html
ctrl + f 可以快速查找
Vuex 使用介绍
安装
npm install vuex@3
新建 store/index.js专门存放 vuex
index.js代码
import Vue from 'vue'
import Vuex from 'vuex'
// vuex也是vue的插件, 需要use一下, 进行插件的安装初始化
Vue.use(Vuex)
// 创建仓库 store
const store = new Vue.Store()
// 导出仓库
export default store
main.js 代码
import Vue from 'vue'
import App from './App.vue'
import store from '@/store/index'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
store
}).$mount('#app')
组件代码
Son1.vue 代码
<template>
<div class="box">
<h2>Son1 子组件</h2>
从vuex中获取的值: <label></label>
<br>
<button>值 + 1</button>
</div>
</template>
<script>
export default {
name: 'Son1Com'
}
</script>
<style lang="css" scoped>
.box{
border: 3px solid #ccc;
width: 400px;
padding: 10px;
margin: 20px;
}
h2 {
margin-top: 10px;
}
</style>
Son2.vue 代码
<template>
<div class="box">
<h2>Son2 子组件</h2>
从vuex中获取的值:<label></label>
<br />
<button>值 - 1</button>
</div>
</template>
<script>
export default {
name: 'Son2Com'
}
</script>
<style lang="css" scoped>
.box {
border: 3px solid #ccc;
width: 400px;
padding: 10px;
margin: 20px;
}
h2 {
margin-top: 10px;
}
</style>
App.vue 代码
<template>
<div id="app">
<h1>根组件</h1>
<input type="text">
<Son1></Son1>
<hr>
<Son2></Son2>
</div>
</template>
<script>
import Son1 from './components/Son1.vue'
import Son2 from './components/Son2.vue'
export default {
name: 'app',
data: function () {
return {
}
},
components: {
Son1,
Son2
}
}
</script>
<style>
#app {
width: 600px;
margin: 20px auto;
border: 3px solid #ccc;
border-radius: 3px;
padding: 10px;
}
</style>
核心概念 - state
State提供唯一的公共数据源,所有共享的数据都要统一放到Store中的State中存储。
使用方法一
使用方法二
核心概念 - mutations
mutations是同步更新数据 (便于监测数据的变化, 更新视图等, 方便于调试工具查看变化)
使用方法一
使用方法二
核心概念 - actions
actions则负责进行异步操作
使用方法一
使用方法二
核心概念 - getters
除了state之外,有时我们还需要从state中筛选出符合条件的一些数据,这些数据是依赖state的,此时会用到getters
使用方法一
使用方法二
核心概念 - module
如果把所有的状态都放在state中,当项目变得越来越大的时候,Vuex会变得越来越难以维护, 由此,又有了Vuex的模块化
`modules/user.js`
const state = {
userInfo: {
name: 'zs',
age: 18
}
}
const mutations = {}
const actions = {}
const getters = {}
export default {
namespaced: true,
state,
mutations,
actions,
getters
}
`modules/setting.js`
const state = {
theme: 'dark'
desc: '描述真呀真不错'
}
const mutations = {}
const actions = {}
const getters = {}
export default {
namespaced: true,
state,
mutations,
actions,
getters
}
`store/index.js`
import user from './modules/user'
import setting from './modules/setting'
const store = new Vuex.Store({
modules:{
user,
setting
}
})
获取模块内的state数据
获取模块内的getters数据
获取模块内的mutations方法
获取模块内的actions方法